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
|
apache__commons-lang
|
src/main/java/org/apache/commons/lang3/exception/UncheckedInterruptedException.java
|
{
"start": 927,
"end": 1446
}
|
class ____ extends UncheckedException {
private static final long serialVersionUID = 1L;
/**
* Constructs an instance initialized to the given {@code cause}.
*
* @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value
* is permitted, and indicates that the cause is nonexistent or unknown.)
*/
public UncheckedInterruptedException(final Throwable cause) {
super(cause);
}
}
|
UncheckedInterruptedException
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/submitted/results_id/Mapper.java
|
{
"start": 987,
"end": 1864
}
|
interface ____ {
// @formatter:off
@Results(id = "userResult", value = {
@Result(id = true, column = "uid", property = "id"),
@Result(column = "name", property = "name")
})
// @formatter:on
@Select("select * from users where uid = #{id}")
User getUserById(Integer id);
@ResultMap("userResult")
@Select("select * from users where name = #{name}")
User getUserByName(String name);
@Results(id = "userResultConstructor")
// @formatter:off
@ConstructorArgs({
@Arg(id = true, column = "uid", javaType = Integer.class),
@Arg(column = "name", javaType = String.class)
})
// @formatter:on
@Select("select * from users where uid = #{id}")
User getUserByIdConstructor(Integer id);
@ResultMap("userResultConstructor")
@Select("select * from users where name = #{name}")
User getUserByNameConstructor(String name);
}
|
Mapper
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/common/network/NioEchoServer.java
|
{
"start": 2662,
"end": 15974
}
|
enum ____ {
TOTAL, RATE, AVG, MAX;
private final String metricNameSuffix = "-" + name().toLowerCase(Locale.ROOT);
public String metricNameSuffix() {
return metricNameSuffix;
}
}
private static final double EPS = 0.0001;
private final int port;
private final ServerSocketChannel serverSocketChannel;
private final List<SocketChannel> newChannels;
private final List<SocketChannel> socketChannels;
private final AcceptorThread acceptorThread;
private final Selector selector;
private volatile TransferableChannel outputChannel;
private final CredentialCache credentialCache;
private final Metrics metrics;
private volatile int numSent = 0;
private volatile boolean closeKafkaChannels;
private final DelegationTokenCache tokenCache;
private final Time time;
private int nextConnectionIndex = 0;
public NioEchoServer(ListenerName listenerName, SecurityProtocol securityProtocol, AbstractConfig config,
String serverHost, ChannelBuilder channelBuilder, CredentialCache credentialCache, Time time) throws Exception {
this(listenerName, securityProtocol, config, serverHost, channelBuilder, credentialCache, 100, time);
}
public NioEchoServer(ListenerName listenerName, SecurityProtocol securityProtocol, AbstractConfig config,
String serverHost, ChannelBuilder channelBuilder, CredentialCache credentialCache,
int failedAuthenticationDelayMs, Time time) throws Exception {
this(listenerName, securityProtocol, config, serverHost, channelBuilder, credentialCache, failedAuthenticationDelayMs, time,
new DelegationTokenCache(ScramMechanism.mechanismNames()));
}
public NioEchoServer(ListenerName listenerName, SecurityProtocol securityProtocol, AbstractConfig config,
String serverHost, ChannelBuilder channelBuilder, CredentialCache credentialCache,
int failedAuthenticationDelayMs, Time time, DelegationTokenCache tokenCache) throws Exception {
super("echoserver");
setDaemon(true);
ServerSocketChannel serverSocketChannel = null;
try {
serverSocketChannel = ServerSocketChannel.open();
this.serverSocketChannel = serverSocketChannel;
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(serverHost, 0));
this.port = serverSocketChannel.socket().getLocalPort();
this.socketChannels = Collections.synchronizedList(new ArrayList<>());
this.newChannels = Collections.synchronizedList(new ArrayList<>());
this.credentialCache = credentialCache;
this.tokenCache = tokenCache;
if (securityProtocol == SecurityProtocol.SASL_PLAINTEXT || securityProtocol == SecurityProtocol.SASL_SSL) {
for (String mechanism : ScramMechanism.mechanismNames()) {
if (credentialCache.cache(mechanism, ScramCredential.class) == null)
credentialCache.createCache(mechanism, ScramCredential.class);
}
}
LogContext logContext = new LogContext();
if (channelBuilder == null)
channelBuilder = ChannelBuilders.serverChannelBuilder(listenerName, false,
securityProtocol, config, credentialCache, tokenCache, time, logContext,
version -> TestUtils.defaultApiVersionsResponse(ApiMessageType.ListenerType.BROKER));
this.metrics = new Metrics();
this.selector = new Selector(10000, failedAuthenticationDelayMs, metrics, time,
"MetricGroup", channelBuilder, logContext);
acceptorThread = new AcceptorThread();
this.time = time;
} catch (Exception e) {
if (serverSocketChannel != null) {
serverSocketChannel.close();
}
throw e;
}
}
public int port() {
return port;
}
public CredentialCache credentialCache() {
return credentialCache;
}
public DelegationTokenCache tokenCache() {
return tokenCache;
}
public double metricValue(String name) {
for (Map.Entry<MetricName, KafkaMetric> entry : metrics.metrics().entrySet()) {
if (entry.getKey().name().equals(name))
return (double) entry.getValue().metricValue();
}
throw new IllegalStateException("Metric not found, " + name + ", found=" + metrics.metrics().keySet());
}
public void verifyAuthenticationMetrics(int successfulAuthentications, final int failedAuthentications)
throws InterruptedException {
waitForMetrics("successful-authentication", successfulAuthentications,
EnumSet.of(MetricType.TOTAL, MetricType.RATE));
waitForMetrics("failed-authentication", failedAuthentications, EnumSet.of(MetricType.TOTAL, MetricType.RATE));
}
public void verifyReauthenticationMetrics(int successfulReauthentications, final int failedReauthentications)
throws InterruptedException {
waitForMetrics("successful-reauthentication", successfulReauthentications,
EnumSet.of(MetricType.TOTAL, MetricType.RATE));
waitForMetrics("failed-reauthentication", failedReauthentications,
EnumSet.of(MetricType.TOTAL, MetricType.RATE));
waitForMetrics("successful-authentication-no-reauth", 0, EnumSet.of(MetricType.TOTAL));
if (!(time instanceof MockTime)) {
waitForMetrics("reauthentication-latency", Math.signum(successfulReauthentications),
EnumSet.of(MetricType.MAX, MetricType.AVG));
}
}
public void waitForMetric(String name, final double expectedValue) throws InterruptedException {
waitForMetrics(name, expectedValue, EnumSet.of(MetricType.TOTAL, MetricType.RATE));
}
public void waitForMetrics(String namePrefix, final double expectedValue, Set<MetricType> metricTypes)
throws InterruptedException {
long maxAggregateWaitMs = 15000;
long startMs = time.milliseconds();
for (MetricType metricType : metricTypes) {
long currentElapsedMs = time.milliseconds() - startMs;
long thisMaxWaitMs = maxAggregateWaitMs - currentElapsedMs;
String metricName = namePrefix + metricType.metricNameSuffix();
if (expectedValue == 0.0) {
double expected = expectedValue;
if (metricType == MetricType.MAX || metricType == MetricType.AVG)
expected = Double.NaN;
assertEquals(expected, metricValue(metricName), EPS, "Metric not updated " + metricName +
" expected:<" + expectedValue + "> but was:<" + metricValue(metricName) + ">");
} else if (metricType == MetricType.TOTAL)
TestUtils.waitForCondition(() -> Math.abs(metricValue(metricName) - expectedValue) <= EPS,
thisMaxWaitMs, () -> "Metric not updated " + metricName + " expected:<" + expectedValue
+ "> but was:<" + metricValue(metricName) + ">");
else
TestUtils.waitForCondition(() -> metricValue(metricName) > 0.0, thisMaxWaitMs,
() -> "Metric not updated " + metricName + " expected:<a positive number> but was:<"
+ metricValue(metricName) + ">");
}
}
@Override
public void run() {
try {
acceptorThread.start();
while (serverSocketChannel.isOpen()) {
selector.poll(100);
synchronized (newChannels) {
for (SocketChannel socketChannel : newChannels) {
selector.register(id(socketChannel), socketChannel);
socketChannels.add(socketChannel);
}
newChannels.clear();
}
if (closeKafkaChannels) {
for (KafkaChannel channel : selector.channels())
selector.close(channel.id());
}
Collection<NetworkReceive> completedReceives = selector.completedReceives();
for (NetworkReceive rcv : completedReceives) {
KafkaChannel channel = channel(rcv.source());
if (!maybeBeginServerReauthentication(channel, rcv, time)) {
String channelId = channel.id();
selector.mute(channelId);
NetworkSend send = new NetworkSend(rcv.source(), ByteBufferSend.sizePrefixed(rcv.payload()));
if (outputChannel == null)
selector.send(send);
else {
send.writeTo(outputChannel);
selector.unmute(channelId);
}
}
}
for (NetworkSend send : selector.completedSends()) {
selector.unmute(send.destinationId());
numSent += 1;
}
}
} catch (IOException e) {
LOG.warn(e.getMessage(), e);
}
}
public int numSent() {
return numSent;
}
private static boolean maybeBeginServerReauthentication(KafkaChannel channel, NetworkReceive networkReceive, Time time) {
try {
if (TestUtils.apiKeyFrom(networkReceive) == ApiKeys.SASL_HANDSHAKE) {
return channel.maybeBeginServerReauthentication(networkReceive, time::nanoseconds);
}
} catch (Exception e) {
// ignore
}
return false;
}
private String id(SocketChannel channel) {
String connectionId = ServerConnectionId.generateConnectionId(channel.socket(), 0, nextConnectionIndex);
if (nextConnectionIndex == Integer.MAX_VALUE)
nextConnectionIndex = 0;
else
nextConnectionIndex = nextConnectionIndex + 1;
return connectionId;
}
private KafkaChannel channel(String id) {
KafkaChannel channel = selector.channel(id);
return channel == null ? selector.closingChannel(id) : channel;
}
/**
* Sets the output channel to which messages received on this server are echoed.
* This is useful in tests where the clients sending the messages don't receive
* the responses (eg. testing graceful close).
*/
public void outputChannel(WritableByteChannel channel) {
this.outputChannel = new TransferableChannel() {
@Override
public boolean hasPendingWrites() {
return false;
}
@Override
public long transferFrom(FileChannel fileChannel, long position, long count) throws IOException {
return fileChannel.transferTo(position, count, channel);
}
@Override
public boolean isOpen() {
return channel.isOpen();
}
@Override
public void close() throws IOException {
channel.close();
}
@Override
public int write(ByteBuffer src) throws IOException {
return channel.write(src);
}
@Override
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
long result = 0;
for (int i = offset; i < offset + length; ++i)
result += write(srcs[i]);
return result;
}
@Override
public long write(ByteBuffer[] srcs) throws IOException {
return write(srcs, 0, srcs.length);
}
};
}
public Selector selector() {
return selector;
}
public void closeKafkaChannels() {
closeKafkaChannels = true;
selector.wakeup();
try {
TestUtils.waitForCondition(() -> selector.channels().isEmpty(), "Channels not closed");
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
closeKafkaChannels = false;
}
}
public void closeSocketChannels() throws IOException {
synchronized (socketChannels) {
for (SocketChannel channel : socketChannels) {
channel.close();
}
socketChannels.clear();
}
}
public void closeNewChannels() throws IOException {
synchronized (newChannels) {
for (SocketChannel channel : newChannels) {
channel.close();
}
newChannels.clear();
}
}
public void close() throws IOException, InterruptedException {
this.serverSocketChannel.close();
closeSocketChannels();
Utils.closeQuietly(selector, "selector");
acceptorThread.interrupt();
acceptorThread.join();
closeNewChannels();
interrupt();
join();
}
private
|
MetricType
|
java
|
elastic__elasticsearch
|
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/EmptyExponentialHistogram.java
|
{
"start": 1498,
"end": 2762
}
|
class ____ implements Buckets {
private static final EmptyBuckets INSTANCE = new EmptyBuckets();
private static final CopyableBucketIterator EMPTY_ITERATOR = new BucketArrayIterator(SCALE, new long[0], new long[0], 0, 0);
@Override
public CopyableBucketIterator iterator() {
return EMPTY_ITERATOR;
}
@Override
public OptionalLong maxBucketIndex() {
return OptionalLong.empty();
}
@Override
public long valueCount() {
return 0;
}
}
@Override
public void close() {}
@Override
public int scale() {
return SCALE;
}
@Override
public ZeroBucket zeroBucket() {
return ZeroBucket.minimalEmpty();
}
@Override
public Buckets positiveBuckets() {
return EmptyBuckets.INSTANCE;
}
@Override
public Buckets negativeBuckets() {
return EmptyBuckets.INSTANCE;
}
@Override
public double sum() {
return 0;
}
@Override
public double min() {
return Double.NaN;
}
@Override
public double max() {
return Double.NaN;
}
@Override
public long ramBytesUsed() {
return 0;
}
}
|
EmptyBuckets
|
java
|
apache__camel
|
core/camel-management/src/test/java/org/apache/camel/management/ManagedSanitizeTest.java
|
{
"start": 1374,
"end": 2615
}
|
class ____ extends ManagementTestSupport {
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
context.getManagementStrategy().getManagementAgent().setMask(true);
return context;
}
@Test
public void testSanitize() throws Exception {
MBeanServer mbeanServer = getMBeanServer();
ObjectName name = getCamelObjectName(TYPE_ENDPOINT, "stub://foo\\?password=xxxxxx&username=xxxxxx");
assertTrue(mbeanServer.isRegistered(name), "Should be registered");
String uri = (String) mbeanServer.getAttribute(name, "EndpointUri");
assertEquals("stub://foo?password=xxxxxx&username=xxxxxx", uri);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").routeId("foo")
.to("stub:foo?username=foo&password=secret")
.to("mock:result");
from("stub:foo?username=foo&password=secret").routeId("stub")
.to("mock:stub");
}
};
}
}
|
ManagedSanitizeTest
|
java
|
quarkusio__quarkus
|
extensions/devui/deployment/src/main/java/io/quarkus/vertx/http/deployment/devmode/NotFoundProcessor.java
|
{
"start": 1275,
"end": 4877
}
|
class ____ {
private static final String META_INF_RESOURCES = "META-INF/resources";
@BuildStep(onlyIf = IsDevelopment.class)
AdditionalBeanBuildItem resourceNotFoundDataAvailable() {
return AdditionalBeanBuildItem.builder()
.addBeanClass(ResourceNotFoundData.class)
.setUnremovable().build();
}
@BuildStep(onlyIf = IsDevelopment.class)
@Record(RUNTIME_INIT)
void routeNotFound(ResourceNotFoundRecorder recorder,
VertxWebRouterBuildItem router,
HttpRootPathBuildItem httpRoot,
BeanContainerBuildItem beanContainer,
LaunchModeBuildItem launchMode,
ApplicationArchivesBuildItem applicationArchivesBuildItem,
List<RouteDescriptionBuildItem> routeDescriptions,
List<NotFoundPageDisplayableEndpointBuildItem> additionalEndpoints) {
// Route Endpoints
List<RouteDescription> routes = new ArrayList<>();
for (RouteDescriptionBuildItem description : routeDescriptions) {
routes.add(description.getDescription());
}
// Static files
Set<String> staticRoots = applicationArchivesBuildItem.getAllApplicationArchives().stream()
.map(i -> i.apply(t -> {
var p = t.getPath(META_INF_RESOURCES);
return p == null ? null : p.toAbsolutePath().toString();
}))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
String baseUrl = getBaseUrl(launchMode);
// Additional endpoints
List<AdditionalRouteDescription> endpoints = additionalEndpoints
.stream()
.map(v -> new AdditionalRouteDescription(concatenateUrl(baseUrl, v.getEndpoint(httpRoot)), v.getDescription()))
.sorted()
.collect(Collectors.toList());
// Not found handler
Handler<RoutingContext> notFoundHandler = recorder.registerNotFoundHandler(
router.getHttpRouter(),
router.getMainRouter(),
router.getManagementRouter(),
beanContainer.getValue(),
baseUrl,
httpRoot.getRootPath(),
routes,
staticRoots,
endpoints);
}
private String getBaseUrl(LaunchModeBuildItem launchMode) {
DevModeType type = launchMode.getDevModeType().orElse(DevModeType.LOCAL);
if (!type.equals(DevModeType.REMOTE_SERVER_SIDE)) {
Config config = ConfigProvider.getConfig();
var host = config.getOptionalValue("quarkus.http.host", String.class).orElse("localhost");
var port = config.getOptionalValue("quarkus.http.port", Integer.class).orElse(8080);
return "http://" + host + ":" + port + "/";
} else {
return null;
}
}
private String concatenateUrl(String part1, String part2) {
if (part1 == null && part2 == null)
return null;
if (part1 == null && part2 != null)
return part2;
if (part1 != null && part2 == null)
return part1;
if (part2.startsWith("http://") || part2.startsWith("https://"))
return part2;
if (part1.endsWith("/") && part2.startsWith("/")) {
return part1.substring(0, part1.length() - 1) + part2;
} else if (!part1.endsWith("/") && !part2.startsWith("/")) {
return part1 + "/" + part2;
} else {
return part1 + part2;
}
}
}
|
NotFoundProcessor
|
java
|
spring-projects__spring-boot
|
module/spring-boot-micrometer-metrics/src/main/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/humio/HumioProperties.java
|
{
"start": 1231,
"end": 2568
}
|
class ____ extends StepRegistryProperties {
/**
* Humio API token.
*/
private @Nullable String apiToken;
/**
* Connection timeout for requests to this backend.
*/
private Duration connectTimeout = Duration.ofSeconds(5);
/**
* Humio tags describing the data source in which metrics will be stored. Humio tags
* are a distinct concept from Micrometer's tags. Micrometer's tags are used to divide
* metrics along dimensional boundaries.
*/
private Map<String, String> tags = new HashMap<>();
/**
* URI to ship metrics to. If you need to publish metrics to an internal proxy
* en-route to Humio, you can define the location of the proxy with this.
*/
private String uri = "https://cloud.humio.com";
public @Nullable String getApiToken() {
return this.apiToken;
}
public void setApiToken(@Nullable String apiToken) {
this.apiToken = apiToken;
}
@Override
public Duration getConnectTimeout() {
return this.connectTimeout;
}
@Override
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Map<String, String> getTags() {
return this.tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
|
HumioProperties
|
java
|
spring-projects__spring-security
|
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/BaseOpenSamlLogoutRequestResolver.java
|
{
"start": 10159,
"end": 11006
}
|
class ____ {
private final HttpServletRequest request;
private final RelyingPartyRegistration registration;
private final Authentication authentication;
private final LogoutRequest logoutRequest;
LogoutRequestParameters(HttpServletRequest request, RelyingPartyRegistration registration,
Authentication authentication, LogoutRequest logoutRequest) {
this.request = request;
this.registration = registration;
this.authentication = authentication;
this.logoutRequest = logoutRequest;
}
HttpServletRequest getRequest() {
return this.request;
}
RelyingPartyRegistration getRelyingPartyRegistration() {
return this.registration;
}
Authentication getAuthentication() {
return this.authentication;
}
LogoutRequest getLogoutRequest() {
return this.logoutRequest;
}
}
}
|
LogoutRequestParameters
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesPodsEndpointBuilderFactory.java
|
{
"start": 54302,
"end": 54659
}
|
class ____ extends AbstractEndpointBuilder implements KubernetesPodsEndpointBuilder, AdvancedKubernetesPodsEndpointBuilder {
public KubernetesPodsEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new KubernetesPodsEndpointBuilderImpl(path);
}
}
|
KubernetesPodsEndpointBuilderImpl
|
java
|
apache__flink
|
flink-python/src/main/java/org/apache/flink/streaming/api/utils/PythonTypeUtils.java
|
{
"start": 44005,
"end": 44765
}
|
class ____ extends DataConverter<Float, Double> {
private static final long serialVersionUID = 1L;
public static final FloatDataConverter INSTANCE = new FloatDataConverter();
@Override
public Float toInternal(Double value) {
if (value == null) {
return null;
}
return value.floatValue();
}
@Override
public Double toExternal(Float value) {
if (value == null) {
return null;
}
return value.doubleValue();
}
}
/**
* Row Data will be converted to the Object Array [RowKind(as Long Object), Field Values(as
* Object Array)].
*/
public static final
|
FloatDataConverter
|
java
|
quarkusio__quarkus
|
extensions/websockets-next/spi/src/main/java/io/quarkus/websockets/next/runtime/spi/telemetry/EndpointKind.java
|
{
"start": 66,
"end": 111
}
|
enum ____ {
SERVER,
CLIENT
}
|
EndpointKind
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FsUrlStreamHandlerFactory.java
|
{
"start": 2096,
"end": 3746
}
|
class ____.
private Configuration conf;
// This map stores whether a protocol is know or not by FileSystem
private Map<String, Boolean> protocols =
new ConcurrentHashMap<String, Boolean>();
// The URL Stream handler
private java.net.URLStreamHandler handler;
public FsUrlStreamHandlerFactory() {
this(new Configuration());
}
public FsUrlStreamHandlerFactory(Configuration conf) {
this.conf = new Configuration(conf);
// force init of FileSystem code to avoid HADOOP-9041
try {
FileSystem.getFileSystemClass("file", conf);
} catch (IOException io) {
throw new RuntimeException(io);
}
this.handler = new FsUrlStreamHandler(this.conf);
for (String protocol : UNEXPORTED_PROTOCOLS) {
protocols.put(protocol, false);
}
}
@Override
public java.net.URLStreamHandler createURLStreamHandler(String protocol) {
LOG.debug("Creating handler for protocol {}", protocol);
if (!protocols.containsKey(protocol)) {
boolean known = true;
try {
Class<? extends FileSystem> impl
= FileSystem.getFileSystemClass(protocol, conf);
LOG.debug("Found implementation of {}: {}", protocol, impl);
}
catch (IOException ex) {
known = false;
}
protocols.put(protocol, known);
}
if (protocols.get(protocol)) {
LOG.debug("Using handler for protocol {}", protocol);
return handler;
} else {
// FileSystem does not know the protocol, let the VM handle this
LOG.debug("Unknown protocol {}, delegating to default implementation",
protocol);
return null;
}
}
}
|
names
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/operators/windowing/WindowOperatorContractTest.java
|
{
"start": 135353,
"end": 147480
}
|
class ____ implements AggregateFunction<String, String, String> {
@Override
public String createAccumulator() {
return null;
}
@Override
public String add(String value, String accumulator) {
return null;
}
@Override
public String getResult(String accumulator) {
return null;
}
@Override
public String merge(String a, String b) {
return null;
}
}
WindowAssigner<Integer, TimeWindow> mockAssigner = mockTimeWindowAssigner();
Trigger<Integer, TimeWindow> mockTrigger = mockTrigger();
InternalWindowFunction<Iterable<Integer>, Void, Integer, TimeWindow> mockWindowFunction =
mockWindowFunction();
KeyedOneInputStreamOperatorTestHarness<Integer, Integer, Void> testHarness =
createWindowOperator(mockAssigner, mockTrigger, 20L, mockWindowFunction);
testHarness.open();
when(mockTrigger.onElement(anyInt(), anyLong(), anyTimeWindow(), anyTriggerContext()))
.thenReturn(TriggerResult.FIRE);
when(mockAssigner.assignWindows(anyInt(), anyLong(), anyAssignerContext()))
.thenReturn(List.of(new TimeWindow(0, 20)));
AtomicBoolean processWasInvoked = new AtomicBoolean(false);
doAnswer(
new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock)
throws Throwable {
InternalWindowFunction.InternalWindowContext context =
(InternalWindowFunction.InternalWindowContext)
invocationOnMock.getArguments()[2];
KeyedStateStore windowKeyedStateStore = context.windowState();
KeyedStateStore globalKeyedStateStore = context.globalState();
ListStateDescriptor<String> windowListStateDescriptor =
new ListStateDescriptor<String>(
"windowListState", String.class);
ListStateDescriptor<String> globalListStateDescriptor =
new ListStateDescriptor<String>(
"globalListState", String.class);
assertThat(
windowKeyedStateStore.getListState(
windowListStateDescriptor))
.hasSameClassAs(
globalKeyedStateStore.getListState(
globalListStateDescriptor));
ValueStateDescriptor<String> windowValueStateDescriptor =
new ValueStateDescriptor<String>(
"windowValueState", String.class);
ValueStateDescriptor<String> globalValueStateDescriptor =
new ValueStateDescriptor<String>(
"globalValueState", String.class);
assertThat(
windowKeyedStateStore.getState(
windowValueStateDescriptor))
.hasSameClassAs(
globalKeyedStateStore.getState(
globalValueStateDescriptor));
AggregatingStateDescriptor<String, String, String>
windowAggStateDesc =
new AggregatingStateDescriptor<
String, String, String>(
"windowAgg",
new NoOpAggregateFunction(),
String.class);
AggregatingStateDescriptor<String, String, String>
globalAggStateDesc =
new AggregatingStateDescriptor<
String, String, String>(
"globalAgg",
new NoOpAggregateFunction(),
String.class);
assertThat(
windowKeyedStateStore.getAggregatingState(
windowAggStateDesc))
.hasSameClassAs(
globalKeyedStateStore.getAggregatingState(
globalAggStateDesc));
ReducingStateDescriptor<String> windowReducingStateDesc =
new ReducingStateDescriptor<String>(
"windowReducing", (a, b) -> a, String.class);
ReducingStateDescriptor<String> globalReducingStateDesc =
new ReducingStateDescriptor<String>(
"globalReducing", (a, b) -> a, String.class);
assertThat(
windowKeyedStateStore.getReducingState(
windowReducingStateDesc))
.hasSameClassAs(
globalKeyedStateStore.getReducingState(
globalReducingStateDesc));
MapStateDescriptor<String, String> windowMapStateDescriptor =
new MapStateDescriptor<String, String>(
"windowMapState", String.class, String.class);
MapStateDescriptor<String, String> globalMapStateDescriptor =
new MapStateDescriptor<String, String>(
"globalMapState", String.class, String.class);
assertThat(
windowKeyedStateStore.getMapState(
windowMapStateDescriptor))
.hasSameClassAs(
globalKeyedStateStore.getMapState(
globalMapStateDescriptor));
processWasInvoked.set(true);
return null;
}
})
.when(mockWindowFunction)
.process(
anyInt(),
anyTimeWindow(),
anyInternalWindowContext(),
anyIntIterable(),
WindowOperatorContractTest.anyCollector());
testHarness.processElement(new StreamRecord<>(0, 0L));
assertThat(processWasInvoked).isTrue();
}
public void testCurrentTimeQuerying(final TimeDomainAdaptor timeAdaptor) throws Exception {
WindowAssigner<Integer, TimeWindow> mockAssigner = mockTimeWindowAssigner();
timeAdaptor.setIsEventTime(mockAssigner);
Trigger<Integer, TimeWindow> mockTrigger = mockTrigger();
InternalWindowFunction<Iterable<Integer>, Void, Integer, TimeWindow> mockWindowFunction =
mockWindowFunction();
final KeyedOneInputStreamOperatorTestHarness<Integer, Integer, Void> testHarness =
createWindowOperator(mockAssigner, mockTrigger, 20L, mockWindowFunction);
testHarness.open();
shouldFireOnElement(mockTrigger);
when(mockAssigner.assignWindows(anyInt(), anyLong(), anyAssignerContext()))
.thenReturn(List.of(new TimeWindow(0, 20)));
doAnswer(
new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock)
throws Throwable {
InternalWindowFunction.InternalWindowContext context =
(InternalWindowFunction.InternalWindowContext)
invocationOnMock.getArguments()[2];
timeAdaptor.verifyCorrectTime(testHarness, context);
return null;
}
})
.when(mockWindowFunction)
.process(
anyInt(),
anyTimeWindow(),
anyInternalWindowContext(),
anyIntIterable(),
WindowOperatorContractTest.anyCollector());
doAnswer(
new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock)
throws Throwable {
InternalWindowFunction.InternalWindowContext context =
(InternalWindowFunction.InternalWindowContext)
invocationOnMock.getArguments()[1];
timeAdaptor.verifyCorrectTime(testHarness, context);
return null;
}
})
.when(mockWindowFunction)
.clear(anyTimeWindow(), anyInternalWindowContext());
timeAdaptor.advanceTime(testHarness, 10);
testHarness.processElement(new StreamRecord<>(0, 0L));
verify(mockWindowFunction, times(1))
.process(
anyInt(),
anyTimeWindow(),
anyInternalWindowContext(),
anyIntIterable(),
WindowOperatorContractTest.anyCollector());
timeAdaptor.advanceTime(testHarness, 100);
verify(mockWindowFunction, times(1)).clear(anyTimeWindow(), anyInternalWindowContext());
}
protected abstract <W extends Window, OUT>
KeyedOneInputStreamOperatorTestHarness<Integer, Integer, OUT> createWindowOperator(
WindowAssigner<Integer, W> assigner,
Trigger<Integer, W> trigger,
long allowedLateness,
InternalWindowFunction<Iterable<Integer>, OUT, Integer, W> windowFunction,
OutputTag<Integer> lateOutputTag)
throws Exception;
protected abstract <W extends Window, OUT>
KeyedOneInputStreamOperatorTestHarness<Integer, Integer, OUT> createWindowOperator(
WindowAssigner<Integer, W> assigner,
Trigger<Integer, W> trigger,
long allowedLatenss,
InternalWindowFunction<Iterable<Integer>, OUT, Integer, W> windowFunction)
throws Exception;
private
|
NoOpAggregateFunction
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java
|
{
"start": 4099,
"end": 4193
}
|
class ____ {
}
@EnableManagementContext(ManagementContextType.SAME)
static
|
EnableChildContext
|
java
|
spring-projects__spring-framework
|
spring-beans/src/main/java/org/springframework/beans/factory/support/LookupOverride.java
|
{
"start": 1671,
"end": 4034
}
|
class ____ extends MethodOverride {
private final @Nullable String beanName;
private @Nullable Method method;
/**
* Construct a new {@code LookupOverride}.
* @param methodName the name of the method to override
* @param beanName the name of the bean in the current {@code BeanFactory} that the
* overridden method should return (may be {@code null} for type-based bean retrieval)
*/
public LookupOverride(String methodName, @Nullable String beanName) {
super(methodName);
this.beanName = beanName;
}
/**
* Construct a new {@code LookupOverride}.
* @param method the method declaration to override
* @param beanName the name of the bean in the current {@code BeanFactory} that the
* overridden method should return (may be {@code null} for type-based bean retrieval)
*/
public LookupOverride(Method method, @Nullable String beanName) {
super(method.getName());
this.method = method;
this.beanName = beanName;
}
/**
* Return the name of the bean that should be returned by this {@code LookupOverride}.
*/
public @Nullable String getBeanName() {
return this.beanName;
}
/**
* Match the specified method by {@link Method} reference or method name.
* <p>For backwards compatibility reasons, in a scenario with overloaded
* non-abstract methods of the given name, only the no-arg variant of a
* method will be turned into a container-driven lookup method.
* <p>In case of a provided {@link Method}, only straight matches will
* be considered, usually demarcated by the {@code @Lookup} annotation.
*/
@Override
public boolean matches(Method method) {
if (this.method != null) {
return method.equals(this.method);
}
else {
return (method.getName().equals(getMethodName()) && (!isOverloaded() ||
Modifier.isAbstract(method.getModifiers()) || method.getParameterCount() == 0));
}
}
@Override
public boolean equals(@Nullable Object other) {
return (other instanceof LookupOverride that && super.equals(other) &&
ObjectUtils.nullSafeEquals(this.method, that.method) &&
ObjectUtils.nullSafeEquals(this.beanName, that.beanName));
}
@Override
public int hashCode() {
return super.hashCode() * 29 + ObjectUtils.nullSafeHashCode(this.beanName);
}
@Override
public String toString() {
return "LookupOverride for method '" + getMethodName() + "'";
}
}
|
LookupOverride
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/search/crossproject/CrossProjectIndexResolutionValidator.java
|
{
"start": 1605,
"end": 2562
}
|
class ____ consistent error handling for scenarios where index resolution
* spans multiple projects, taking into account the provided {@link IndicesOptions}.
* It handles:
* <ul>
* <li>Validation of index existence in both origin and linked projects based on IndicesOptions
* (ignoreUnavailable, allowNoIndices)</li>
* <li>Authorization issues during cross-project index resolution, returning appropriate
* {@link ElasticsearchSecurityException} responses</li>
* <li>Both flat (unqualified) and qualified index expressions (including "_origin:" prefixed indices)</li>
* <li>Wildcard index patterns that may resolve differently across projects</li>
* </ul>
* <p>
* The validator examines both local and remote resolution results to determine the appropriate
* error response, returning {@link IndexNotFoundException} for missing indices or
* {@link ElasticsearchSecurityException} for authorization failures.
*/
public
|
provides
|
java
|
apache__camel
|
components/camel-reactive-streams/src/main/java/org/apache/camel/component/reactive/streams/util/UnwrapStreamProcessor.java
|
{
"start": 1251,
"end": 3519
}
|
class ____ extends AsyncProcessorSupport {
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
Object content = exchange.getIn().getBody();
if (content instanceof Publisher) {
Publisher<?> pub = Publisher.class.cast(content);
List<Object> data = new LinkedList<>();
pub.subscribe(new Subscriber<Object>() {
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(Object o) {
data.add(o);
}
@Override
public void onError(Throwable throwable) {
addData();
exchange.setException(throwable);
callback.done(false);
}
@Override
public void onComplete() {
addData();
callback.done(false);
}
private void addData() {
Object body;
if (data.isEmpty()) {
body = null;
} else if (data.size() == 1) {
body = data.get(0);
} else {
body = data;
}
if (body instanceof Exchange && !exchange.equals(body)) {
// copy into the original Exchange
Exchange copy = (Exchange) body;
exchange.setException(copy.getException());
exchange.setIn(copy.getIn());
if (copy.hasOut()) {
exchange.setOut(copy.getOut());
}
exchange.getProperties().clear();
exchange.getProperties().putAll(copy.getProperties());
} else {
exchange.getMessage().setBody(body);
}
}
});
return false;
}
callback.done(true);
return true;
}
}
|
UnwrapStreamProcessor
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/main/java/org/apache/camel/builder/component/AbstractComponentBuilder.java
|
{
"start": 989,
"end": 1039
}
|
class ____ component builders.
*/
public abstract
|
for
|
java
|
apache__maven
|
compat/maven-compat/src/main/java/org/apache/maven/repository/metadata/MetadataTreeNode.java
|
{
"start": 1009,
"end": 3980
}
|
class ____ {
ArtifactMetadata md; // this node
MetadataTreeNode parent; // papa
/** default # of children. Used for tree creation optimization only */
int nChildren = 8;
MetadataTreeNode[] children; // of cause
public int getNChildren() {
return nChildren;
}
public void setNChildren(int children) {
nChildren = children;
}
// ------------------------------------------------------------------------
public MetadataTreeNode() {}
// ------------------------------------------------------------------------
public MetadataTreeNode(ArtifactMetadata md, MetadataTreeNode parent, boolean resolved, ArtifactScopeEnum scope) {
if (md != null) {
md.setArtifactScope(ArtifactScopeEnum.checkScope(scope));
md.setResolved(resolved);
}
this.md = md;
this.parent = parent;
}
// ------------------------------------------------------------------------
public MetadataTreeNode(Artifact af, MetadataTreeNode parent, boolean resolved, ArtifactScopeEnum scope) {
this(new ArtifactMetadata(af), parent, resolved, scope);
}
// ------------------------------------------------------------------------
public void addChild(int index, MetadataTreeNode kid) {
if (kid == null) {
return;
}
if (children == null) {
children = new MetadataTreeNode[nChildren];
}
children[index % nChildren] = kid;
}
// ------------------------------------------------------------------
@Override
public String toString() {
return md == null ? "no metadata" : md.toString();
}
// ------------------------------------------------------------------
public String graphHash() throws MetadataResolutionException {
if (md == null) {
throw new MetadataResolutionException(
"treenode without metadata, parent: " + (parent == null ? "null" : parent.toString()));
}
return md.groupId + ":" + md.artifactId;
}
// ------------------------------------------------------------------------
public boolean hasChildren() {
return children != null;
}
// ------------------------------------------------------------------------
public ArtifactMetadata getMd() {
return md;
}
public void setMd(ArtifactMetadata md) {
this.md = md;
}
public MetadataTreeNode getParent() {
return parent;
}
public void setParent(MetadataTreeNode parent) {
this.parent = parent;
}
public MetadataTreeNode[] getChildren() {
return children;
}
public void setChildren(MetadataTreeNode[] children) {
this.children = children;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
}
|
MetadataTreeNode
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/configuration/MetricOptions.java
|
{
"start": 4167,
"end": 24056
}
|
class ____ use for the reporter named <name>.");
@Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX)
@Documentation.Section(value = Documentation.Sections.METRIC_REPORTERS, position = 2)
public static final ConfigOption<Duration> REPORTER_INTERVAL =
key("interval")
.durationType()
.defaultValue(Duration.ofSeconds(10))
.withDescription(
"The reporter interval to use for the reporter named <name>. Only applicable to push-based reporters.");
@Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX)
@Documentation.Section(value = Documentation.Sections.METRIC_REPORTERS, position = 2)
public static final ConfigOption<String> REPORTER_SCOPE_DELIMITER =
key("scope.delimiter")
.stringType()
.defaultValue(".")
.withDescription(
"The delimiter used to assemble the metric identifier for the reporter named <name>.");
@Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX)
@Documentation.Section(value = Documentation.Sections.METRIC_REPORTERS, position = 3)
public static final ConfigOption<Map<String, String>> REPORTER_ADDITIONAL_VARIABLES =
key("scope.variables.additional")
.mapType()
.defaultValue(Collections.emptyMap())
.withDescription(
"The map of additional variables that should be included for the reporter named <name>. Only applicable to tag-based reporters.");
@Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX)
@Documentation.Section(value = Documentation.Sections.METRIC_REPORTERS, position = 3)
public static final ConfigOption<String> REPORTER_EXCLUDED_VARIABLES =
key("scope.variables.excludes")
.stringType()
.defaultValue(".")
.withDescription(
"The set of variables that should be excluded for the reporter named <name>. Only applicable to tag-based reporters.");
@Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX)
@Documentation.Section(value = Documentation.Sections.METRIC_REPORTERS, position = 4)
public static final ConfigOption<List<String>> REPORTER_INCLUDES =
key("filter.includes")
.stringType()
.asList()
.defaultValues("*:*:*")
.withDescription(
Description.builder()
.text(
"The metrics that should be included for the reporter named <name>."
+ " Filters are specified as a list, with each filter following this format:")
.linebreak()
.text("%s", code("<scope>[:<name>[,<name>][:<type>[,<type>]]]"))
.linebreak()
.text(
"A metric matches a filter if the scope pattern and at least one of the name patterns and at least one of the types match.")
.linebreak()
.list(
text(
"scope: Filters based on the logical scope.%s"
+ "Specified as a pattern where %s matches any sequence of characters and %s separates scope components.%s%s"
+ "For example:%s"
+ " \"%s\" matches any job-related metrics on the JobManager,%s"
+ " \"%s\" matches all job-related metrics and%s"
+ " \"%s\" matches all metrics below the job-level (i.e., task/operator metrics etc.).%s%s",
linebreak(),
code("*"),
code("."),
linebreak(),
linebreak(),
linebreak(),
code("jobmanager.job"),
linebreak(),
code("*.job"),
linebreak(),
code("*.job.*"),
linebreak(),
linebreak()),
text(
"name: Filters based on the metric name.%s"
+ "Specified as a comma-separate list of patterns where %s matches any sequence of characters.%s%s"
+ "For example, \"%s\" matches any metrics where the name contains %s.%s%s",
linebreak(),
code("*"),
linebreak(),
linebreak(),
code("*Records*,*Bytes*"),
code("\"Records\" or \"Bytes\""),
linebreak(),
linebreak()),
text(
"type: Filters based on the metric type. Specified as a comma-separated list of metric types: %s",
code("[counter, meter, gauge, histogram]")))
.text("Examples:")
.list(
text(
"\"%s\" Matches metrics like %s.",
code("*:numRecords*"), code("numRecordsIn")),
text(
"\"%s\" Matches metrics like %s on the operator level.",
code("*.job.task.operator:numRecords*"),
code("numRecordsIn")),
text(
"\"%s\" Matches meter metrics like %s on the operator level.",
code("*.job.task.operator:numRecords*:meter"),
code("numRecordsInPerSecond")),
text(
"\"%s\" Matches all counter/meter metrics like or %s.",
code("*:numRecords*,numBytes*:counter,meter"),
code("numRecordsInPerSecond"),
code("numBytesOut")))
.build());
@Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX)
@Documentation.Section(value = Documentation.Sections.METRIC_REPORTERS, position = 5)
public static final ConfigOption<List<String>> REPORTER_EXCLUDES =
key("filter.excludes")
.stringType()
.asList()
.defaultValues()
.withDescription(
Description.builder()
.text(
"The metrics that should be excluded for the reporter named <name>. The format is identical to %s",
code(REPORTER_INCLUDES.key()))
.linebreak()
.build());
@Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX)
@Documentation.Section(value = Documentation.Sections.METRIC_REPORTERS, position = 6)
public static final ConfigOption<String> REPORTER_CONFIG_PARAMETER =
key("<parameter>")
.stringType()
.noDefaultValue()
.withDescription(
"Configures the parameter <parameter> for the reporter named <name>.");
/** The delimiter used to assemble the metric identifier. */
public static final ConfigOption<String> SCOPE_DELIMITER =
key("metrics.scope.delimiter")
.stringType()
.defaultValue(".")
.withDescription("Delimiter used to assemble the metric identifier.");
/** The scope format string that is applied to all metrics scoped to a JobManager. */
public static final ConfigOption<String> SCOPE_NAMING_JM =
key("metrics.scope.jm")
.stringType()
.defaultValue("<host>.jobmanager")
.withDescription(
"Defines the scope format string that is applied to all metrics scoped to a JobManager. Only effective when a identifier-based reporter is configured.");
/** The scope format string that is applied to all metrics scoped to a TaskManager. */
public static final ConfigOption<String> SCOPE_NAMING_TM =
key("metrics.scope.tm")
.stringType()
.defaultValue("<host>.taskmanager.<tm_id>")
.withDescription(
"Defines the scope format string that is applied to all metrics scoped to a TaskManager. Only effective when a identifier-based reporter is configured");
/** The scope format string that is applied to all metrics scoped to a job on a JobManager. */
public static final ConfigOption<String> SCOPE_NAMING_JM_JOB =
key("metrics.scope.jm-job")
.stringType()
.defaultValue("<host>.jobmanager.<job_name>")
.withDeprecatedKeys("metrics.scope.jm.job")
.withDescription(
"Defines the scope format string that is applied to all metrics scoped to a job on a JobManager. Only effective when a identifier-based reporter is configured");
/**
* The scope format string that is applied to all metrics scoped to the components running on a
* JobManager of an operator.
*/
public static final ConfigOption<String> SCOPE_NAMING_JM_OPERATOR =
key("metrics.scope.jm-operator")
.stringType()
.defaultValue("<host>.jobmanager.<job_name>.<operator_name>")
.withDescription(
"Defines the scope format string that is applied to all metrics scoped to the components running on a JobManager of an Operator, like OperatorCoordinator for Source Enumerator metrics.");
/** The scope format string that is applied to all metrics scoped to a job on a TaskManager. */
public static final ConfigOption<String> SCOPE_NAMING_TM_JOB =
key("metrics.scope.tm-job")
.stringType()
.defaultValue("<host>.taskmanager.<tm_id>.<job_name>")
.withDeprecatedKeys("metrics.scope.tm.job")
.withDescription(
"Defines the scope format string that is applied to all metrics scoped to a job on a TaskManager. Only effective when a identifier-based reporter is configured");
/** The scope format string that is applied to all metrics scoped to a task. */
public static final ConfigOption<String> SCOPE_NAMING_TASK =
key("metrics.scope.task")
.stringType()
.defaultValue(
"<host>.taskmanager.<tm_id>.<job_name>.<task_name>.<subtask_index>")
.withDescription(
"Defines the scope format string that is applied to all metrics scoped to a task. Only effective when a identifier-based reporter is configured");
/** The scope format string that is applied to all metrics scoped to an operator. */
public static final ConfigOption<String> SCOPE_NAMING_OPERATOR =
key("metrics.scope.operator")
.stringType()
.defaultValue(
"<host>.taskmanager.<tm_id>.<job_name>.<operator_name>.<subtask_index>")
.withDescription(
"Defines the scope format string that is applied to all metrics scoped to an operator. Only effective when a identifier-based reporter is configured");
public static final ConfigOption<Duration> LATENCY_INTERVAL =
key("metrics.latency.interval")
.durationType()
.defaultValue(Duration.ofMillis(0L))
.withDescription(
"Defines the interval at which latency tracking marks are emitted from the sources."
+ " Disables latency tracking if set to 0 or a negative value. Enabling this feature can significantly"
+ " impact the performance of the cluster.");
public static final ConfigOption<String> LATENCY_SOURCE_GRANULARITY =
key("metrics.latency.granularity")
.stringType()
.defaultValue("operator")
.withDescription(
Description.builder()
.text(
"Defines the granularity of latency metrics. Accepted values are:")
.list(
text(
"single - Track latency without differentiating between sources and subtasks."),
text(
"operator - Track latency while differentiating between sources, but not subtasks."),
text(
"subtask - Track latency while differentiating between sources and subtasks."))
.build());
/** The number of measured latencies to maintain at each operator. */
public static final ConfigOption<Integer> LATENCY_HISTORY_SIZE =
key("metrics.latency.history-size")
.intType()
.defaultValue(128)
.withDescription(
"Defines the number of measured latencies to maintain at each operator.");
/**
* Whether Flink should report system resource metrics such as machine's CPU, memory or network
* usage.
*/
public static final ConfigOption<Boolean> SYSTEM_RESOURCE_METRICS =
key("metrics.system-resource")
.booleanType()
.defaultValue(false)
.withDescription(
"Flag indicating whether Flink should report system resource metrics such as machine's CPU,"
+ " memory or network usage.");
/**
* Interval between probing of system resource metrics specified in milliseconds. Has an effect
* only when {@link #SYSTEM_RESOURCE_METRICS} is enabled.
*/
public static final ConfigOption<Duration> SYSTEM_RESOURCE_METRICS_PROBING_INTERVAL =
key("metrics.system-resource-probing-interval")
.durationType()
.defaultValue(Duration.ofMillis(5000L))
.withDescription(
"Interval between probing of system resource metrics specified. Has an effect"
+ " only when '"
+ SYSTEM_RESOURCE_METRICS.key()
+ "' is enabled.");
/**
* The default network port range for Flink's internal metric query service. The {@code "0"}
* means that Flink searches for a free port.
*/
@Documentation.Section(Documentation.Sections.COMMON_HOST_PORT)
public static final ConfigOption<String> QUERY_SERVICE_PORT =
key("metrics.internal.query-service.port")
.stringType()
.defaultValue("0")
.withDescription(
"The port range used for Flink's internal metric query service. Accepts a list of ports "
+ "(“50100,50101”), ranges(“50100-50200”) or a combination of both. It is recommended to set a range of "
+ "ports to avoid collisions when multiple Flink components are running on the same machine. Per default "
+ "Flink will pick a random port.");
/**
* The thread priority for Flink's internal metric query service. The {@code 1} means the min
* priority and the {@code 10} means the max priority.
*/
public static final ConfigOption<Integer> QUERY_SERVICE_THREAD_PRIORITY =
key("metrics.internal.query-service.thread-priority")
.intType()
.defaultValue(1)
.withDescription(
"The thread priority used for Flink's internal metric query service. The thread is created"
+ " by Pekko's thread pool executor. "
+ "The range of the priority is from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY). "
+ "Warning, increasing this value may bring the main Flink components down.");
/**
* The config parameter defining the update interval for the metric fetcher used by the web UI
* in milliseconds.
*/
public static final ConfigOption<Duration> METRIC_FETCHER_UPDATE_INTERVAL =
key("metrics.fetcher.update-interval")
.durationType()
.defaultValue(Duration.ofMillis(10000L))
.withDescription(
"Update interval for the metric fetcher used by the web UI. Decrease this value for "
+ "faster updating metrics. Increase this value if the metric fetcher causes too much load. Setting this value to 0 "
+ "disables the metric fetching completely.");
/** Controls which job status metrics will be exposed. */
public static final ConfigOption<List<JobStatusMetrics>> JOB_STATUS_METRICS =
key("metrics.job.status.enable")
.enumType(JobStatusMetrics.class)
.asList()
.defaultValues(JobStatusMetrics.CURRENT_TIME)
.withDescription(
"The selection of job status metrics that should be reported.");
/** Enum describing the different kinds of job status metrics. */
public
|
to
|
java
|
bumptech__glide
|
annotation/compiler/test/src/test/java/com/bumptech/glide/annotation/compiler/InvalidGlideOptionsExtensionTest.java
|
{
"start": 2595,
"end": 4010
}
|
class ____{",
" private NonRequestOptionsFirstArgExtension() {}",
" @GlideOption",
" public static BaseRequestOptions<?> doSomething(",
" Object arg1, BaseRequestOptions<?> options) {",
" return options;",
" }",
"}"));
fail();
} catch (RuntimeException e) {
String message = e.getCause().getMessage();
Truth.assertThat(message).contains("BaseRequestOptions<?> object as their first parameter");
Truth.assertThat(message).contains("Object");
Truth.assertThat(message).contains("NonRequestOptionsFirstArgExtension");
}
}
@Test
public void compilation_withAnnotatedStaticMethod_withRequestOptionsArg_succeeds() {
Compilation compilation =
javac()
.withProcessors(new GlideAnnotationProcessor())
.compile(
emptyAppModule(),
JavaFileObjects.forSourceLines(
"Extension",
"package com.bumptech.glide.test;",
"import com.bumptech.glide.annotation.GlideExtension;",
"import com.bumptech.glide.annotation.GlideOption;",
"import com.bumptech.glide.request.BaseRequestOptions;",
"@GlideExtension",
"public
|
NonRequestOptionsFirstArgExtension
|
java
|
apache__rocketmq
|
filter/src/test/java/org/apache/rocketmq/filter/ExpressionTest.java
|
{
"start": 1418,
"end": 30548
}
|
class ____ {
private static String andExpression = "a=3 and b<>4 And c>5 AND d<=4";
private static String orExpression = "a=3 or b<>4 Or c>5 OR d<=4";
private static String inExpression = "a in ('3', '4', '5')";
private static String notInExpression = "a not in ('3', '4', '5')";
private static String betweenExpression = "a between 2 and 10";
private static String notBetweenExpression = "a not between 2 and 10";
private static String isNullExpression = "a is null";
private static String isNotNullExpression = "a is not null";
private static String equalExpression = "a is not null and a='hello'";
private static String booleanExpression = "a=TRUE OR b=FALSE";
private static String nullOrExpression = "a is null OR a='hello'";
private static String stringHasString = "TAGS is not null and TAGS='''''tag'''''";
@Test
public void testContains_StartsWith_EndsWith_has() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", "axb")
);
eval(genExp("value contains 'x'"), context, Boolean.TRUE);
eval(genExp("value startswith 'ax'"), context, Boolean.TRUE);
eval(genExp("value endswith 'xb'"), context, Boolean.TRUE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_has() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", "axb")
);
eval(genExp("value not contains 'x'"), context, Boolean.FALSE);
eval(genExp("value not startswith 'ax'"), context, Boolean.FALSE);
eval(genExp("value not endswith 'xb'"), context, Boolean.FALSE);
}
@Test
public void testContains_StartsWith_EndsWith_has_not() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", "abb")
);
eval(genExp("value contains 'x'"), context, Boolean.FALSE);
eval(genExp("value startswith 'x'"), context, Boolean.FALSE);
eval(genExp("value endswith 'x'"), context, Boolean.FALSE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_has_not() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", "abb")
);
eval(genExp("value not contains 'x'"), context, Boolean.TRUE);
eval(genExp("value not startswith 'x'"), context, Boolean.TRUE);
eval(genExp("value not endswith 'x'"), context, Boolean.TRUE);
}
@Test
public void testContains_StartsWith_EndsWith_hasEmpty() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", "axb")
);
eval(genExp("value contains ''"), context, Boolean.FALSE);
eval(genExp("value startswith ''"), context, Boolean.FALSE);
eval(genExp("value endswith ''"), context, Boolean.FALSE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_hasEmpty() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", "axb")
);
eval(genExp("value not contains ''"), context, Boolean.FALSE);
eval(genExp("value not startswith ''"), context, Boolean.FALSE);
eval(genExp("value not endswith ''"), context, Boolean.FALSE);
}
@Test
public void testContains_StartsWith_EndsWith_null_has_1() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", null)
);
eval(genExp("value contains 'x'"), context, Boolean.FALSE);
eval(genExp("value startswith 'x'"), context, Boolean.FALSE);
eval(genExp("value endswith 'x'"), context, Boolean.FALSE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_null_has_1() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", null)
);
eval(genExp("value not contains 'x'"), context, Boolean.FALSE);
eval(genExp("value not startswith 'x'"), context, Boolean.FALSE);
eval(genExp("value not endswith 'x'"), context, Boolean.FALSE);
}
@Test
public void testContains_StartsWith_EndsWith_null_has_2() throws Exception {
EvaluationContext context = genContext(
// KeyValue.c("value", null)
);
eval(genExp("value contains 'x'"), context, Boolean.FALSE);
eval(genExp("value startswith 'x'"), context, Boolean.FALSE);
eval(genExp("value endswith 'x'"), context, Boolean.FALSE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_null_has_2() throws Exception {
EvaluationContext context = genContext(
// KeyValue.c("value", null)
);
eval(genExp("value not contains 'x'"), context, Boolean.FALSE);
eval(genExp("value not startswith 'x'"), context, Boolean.FALSE);
eval(genExp("value not endswith 'x'"), context, Boolean.FALSE);
}
@Test
public void testContains_StartsWith_EndsWith_number_has() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", 1.23)
);
eval(genExp("value contains 'x'"), context, Boolean.FALSE);
eval(genExp("value startswith 'x'"), context, Boolean.FALSE);
eval(genExp("value endswith 'x'"), context, Boolean.FALSE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_number_has() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", 1.23)
);
eval(genExp("value not contains 'x'"), context, Boolean.FALSE);
eval(genExp("value not startswith 'x'"), context, Boolean.FALSE);
eval(genExp("value not endswith 'x'"), context, Boolean.FALSE);
}
@Test
public void testContains_StartsWith_EndsWith_boolean_has() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", Boolean.TRUE)
);
eval(genExp("value contains 'x'"), context, Boolean.FALSE);
eval(genExp("value startswith 'x'"), context, Boolean.FALSE);
eval(genExp("value endswith 'x'"), context, Boolean.FALSE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_boolean_has() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", Boolean.TRUE)
);
eval(genExp("value not contains 'x'"), context, Boolean.FALSE);
eval(genExp("value not startswith 'x'"), context, Boolean.FALSE);
eval(genExp("value not endswith 'x'"), context, Boolean.FALSE);
}
@Test
public void testContains_StartsWith_EndsWith_object_has() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("value", new Object())
);
eval(genExp("value contains 'x'"), context, Boolean.FALSE);
eval(genExp("value startswith 'x'"), context, Boolean.FALSE);
eval(genExp("value endswith 'x'"), context, Boolean.FALSE);
}
@Test
public void testContains_has_not_string_1() throws Exception {
try {
Expression expr = genExp("value contains x"); // will throw parse exception.
EvaluationContext context = genContext(
KeyValue.c("value", "axb")
);
eval(expr, context, Boolean.FALSE);
} catch (Throwable e) {
}
}
@Test
public void test_notContains_has_not_string_1() throws Exception {
try {
Expression expr = genExp("value not contains x"); // will throw parse exception.
EvaluationContext context = genContext(
KeyValue.c("value", "axb")
);
eval(expr, context, Boolean.FALSE);
} catch (Throwable e) {
}
}
@Test
public void testContains_has_not_string_2() throws Exception {
try {
Expression expr = genExp("value contains 123"); // will throw parse exception.
EvaluationContext context = genContext(
KeyValue.c("value", "axb")
);
eval(expr, context, Boolean.FALSE);
} catch (Throwable e) {
}
}
@Test
public void test_notContains_has_not_string_2() throws Exception {
try {
Expression expr = genExp("value not contains 123"); // will throw parse exception.
EvaluationContext context = genContext(
KeyValue.c("value", "axb")
);
eval(expr, context, Boolean.FALSE);
} catch (Throwable e) {
}
}
@Test
public void testContains_StartsWith_EndsWith_string_has_string() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("'axb' contains 'x'"), context, Boolean.TRUE);
eval(genExp("'axb' startswith 'ax'"), context, Boolean.TRUE);
eval(genExp("'axb' endswith 'xb'"), context, Boolean.TRUE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_string_has_string() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("'axb' not contains 'x'"), context, Boolean.FALSE);
eval(genExp("'axb' not startswith 'ax'"), context, Boolean.FALSE);
eval(genExp("'axb' not endswith 'xb'"), context, Boolean.FALSE);
}
@Test
public void testContains_startsWith_endsWith_string_has_not_string() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("'axb' contains 'u'"), context, Boolean.FALSE);
eval(genExp("'axb' startswith 'u'"), context, Boolean.FALSE);
eval(genExp("'axb' endswith 'u'"), context, Boolean.FALSE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_string_has_not_string() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("'axb' not contains 'u'"), context, Boolean.TRUE);
eval(genExp("'axb' not startswith 'u'"), context, Boolean.TRUE);
eval(genExp("'axb' not endswith 'u'"), context, Boolean.TRUE);
}
@Test
public void testContains_StartsWith_EndsWith_string_has_empty() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("'axb' contains ''"), context, Boolean.FALSE);
eval(genExp("'axb' startswith ''"), context, Boolean.FALSE);
eval(genExp("'axb' endswith ''"), context, Boolean.FALSE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_string_has_empty() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("'axb' not contains ''"), context, Boolean.FALSE);
eval(genExp("'axb' not startswith ''"), context, Boolean.FALSE);
eval(genExp("'axb' not endswith ''"), context, Boolean.FALSE);
}
@Test
public void testContains_StartsWith_EndsWith_string_has_space() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("' ' contains ' '"), context, Boolean.TRUE);
eval(genExp("' ' startswith ' '"), context, Boolean.TRUE);
eval(genExp("' ' endswith ' '"), context, Boolean.TRUE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_string_has_space() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("' ' not contains ' '"), context, Boolean.FALSE);
eval(genExp("' ' not startswith ' '"), context, Boolean.FALSE);
eval(genExp("' ' not endswith ' '"), context, Boolean.FALSE);
}
@Test
public void testContains_string_has_nothing() throws Exception {
try {
Expression expr = genExp("'axb' contains "); // will throw parse exception.
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(expr, context, Boolean.TRUE);
} catch (Throwable e) {
}
}
@Test
public void test_notContains_string_has_nothing() throws Exception {
try {
Expression expr = genExp("'axb' not contains "); // will throw parse exception.
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(expr, context, Boolean.TRUE);
} catch (Throwable e) {
}
}
@Test
public void testContains_StartsWith_EndsWith_string_has_special_1() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("'axb' contains '.'"), context, Boolean.FALSE);
eval(genExp("'axb' startswith '.'"), context, Boolean.FALSE);
eval(genExp("'axb' endswith '.'"), context, Boolean.FALSE);
}
@Test
public void test_notContains_notStartsWith_notEndsWith_string_has_special_1() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("'axb' not contains '.'"), context, Boolean.TRUE);
eval(genExp("'axb' not startswith '.'"), context, Boolean.TRUE);
eval(genExp("'axb' not endswith '.'"), context, Boolean.TRUE);
}
@Test
public void testContains_StartsWith_EndsWith_string_has_special_2() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("whatever", "whatever")
);
eval(genExp("'s' contains '\\'"), context, Boolean.FALSE);
eval(genExp("'s' startswith '\\'"), context, Boolean.FALSE);
eval(genExp("'s' endswith '\\'"), context, Boolean.FALSE);
}
@Test
public void testContainsAllInOne() throws Exception {
Expression expr = genExp("a not in ('4', '4', '5') and b between 3 and 10 and c not contains 'axbc'");
EvaluationContext context = genContext(
KeyValue.c("a", "3"),
KeyValue.c("b", 3),
KeyValue.c("c", "axbdc")
);
eval(expr, context, Boolean.TRUE);
}
@Test
public void testStartsWithAllInOne() throws Exception {
Expression expr = genExp("a not in ('4', '4', '5') and b between 3 and 10 and c not startswith 'axbc'");
EvaluationContext context = genContext(
KeyValue.c("a", "3"),
KeyValue.c("b", 3),
KeyValue.c("c", "axbdc")
);
eval(expr, context, Boolean.TRUE);
}
@Test
public void testEndsWithAllInOne() throws Exception {
Expression expr = genExp("a not in ('4', '4', '5') and b between 3 and 10 and c not endswith 'axbc'");
EvaluationContext context = genContext(
KeyValue.c("a", "3"),
KeyValue.c("b", 3),
KeyValue.c("c", "axbdc")
);
eval(expr, context, Boolean.TRUE);
}
@Test
public void testEvaluate_stringHasString() throws Exception {
Expression expr = genExp(stringHasString);
EvaluationContext context = genContext(
KeyValue.c("TAGS", "''tag''")
);
eval(expr, context, Boolean.TRUE);
}
@Test
public void testEvaluate_now() throws Exception {
EvaluationContext context = genContext(
KeyValue.c("a", System.currentTimeMillis())
);
Expression nowExpression = ConstantExpression.createNow();
Expression propertyExpression = new PropertyExpression("a");
Expression expression = ComparisonExpression.createLessThanEqual(propertyExpression,
nowExpression);
eval(expression, context, Boolean.TRUE);
}
@Test(expected = RuntimeException.class)
public void testEvaluate_stringCompare() throws Exception {
Expression expression = genExp("a between up and low");
EvaluationContext context = genContext(
KeyValue.c("a", "3.14")
);
eval(expression, context, Boolean.FALSE);
{
context = genContext(
KeyValue.c("a", "3.14"),
KeyValue.c("up", "up"),
KeyValue.c("low", "low")
);
eval(expression, context, Boolean.FALSE);
}
{
expression = genExp("key is not null and key between 0 and 100");
context = genContext(
KeyValue.c("key", "con")
);
eval(expression, context, Boolean.FALSE);
}
{
expression = genExp("a between 0 and 100");
context = genContext(
KeyValue.c("a", "abc")
);
eval(expression, context, Boolean.FALSE);
}
{
expression = genExp("a=b");
context = genContext(
KeyValue.c("a", "3.14"),
KeyValue.c("b", "3.14")
);
eval(expression, context, Boolean.TRUE);
}
{
expression = genExp("a<>b");
context = genContext(
KeyValue.c("a", "3.14"),
KeyValue.c("b", "3.14")
);
eval(expression, context, Boolean.FALSE);
}
{
expression = genExp("a<>b");
context = genContext(
KeyValue.c("a", "3.14"),
KeyValue.c("b", "3.141")
);
eval(expression, context, Boolean.TRUE);
}
}
@Test
public void testEvaluate_exponent() throws Exception {
Expression expression = genExp("a > 3.1E10");
EvaluationContext context = genContext(
KeyValue.c("a", String.valueOf(3.1415 * Math.pow(10, 10)))
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_floatNumber() throws Exception {
Expression expression = genExp("a > 3.14");
EvaluationContext context = genContext(
KeyValue.c("a", String.valueOf(3.1415))
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_twoVariable() throws Exception {
Expression expression = genExp("a > b");
EvaluationContext context = genContext(
KeyValue.c("a", String.valueOf(10)),
KeyValue.c("b", String.valueOf(20))
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_twoVariableGt() throws Exception {
Expression expression = genExp("a > b");
EvaluationContext context = genContext(
KeyValue.c("b", String.valueOf(10)),
KeyValue.c("a", String.valueOf(20))
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_nullOr() throws Exception {
Expression expression = genExp(nullOrExpression);
EvaluationContext context = genContext(
);
eval(expression, context, Boolean.TRUE);
context = genContext(
KeyValue.c("a", "hello")
);
eval(expression, context, Boolean.TRUE);
context = genContext(
KeyValue.c("a", "abc")
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_boolean() throws Exception {
Expression expression = genExp(booleanExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "true"),
KeyValue.c("b", "false")
);
eval(expression, context, Boolean.TRUE);
context = genContext(
KeyValue.c("a", "false"),
KeyValue.c("b", "true")
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_equal() throws Exception {
Expression expression = genExp(equalExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "hello")
);
eval(expression, context, Boolean.TRUE);
context = genContext(
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_andTrue() throws Exception {
Expression expression = genExp(andExpression);
EvaluationContext context = genContext(
KeyValue.c("a", 3),
KeyValue.c("b", 5),
KeyValue.c("c", 6),
KeyValue.c("d", 1)
);
for (int i = 0; i < 500; i++) {
eval(expression, context, Boolean.TRUE);
}
long start = System.currentTimeMillis();
for (int j = 0; j < 100; j++) {
for (int i = 0; i < 1000; i++) {
eval(expression, context, Boolean.TRUE);
}
}
// use string
context = genContext(
KeyValue.c("a", "3"),
KeyValue.c("b", "5"),
KeyValue.c("c", "6"),
KeyValue.c("d", "1")
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_andFalse() throws Exception {
Expression expression = genExp(andExpression);
EvaluationContext context = genContext(
KeyValue.c("a", 4),
KeyValue.c("b", 5),
KeyValue.c("c", 6),
KeyValue.c("d", 1)
);
eval(expression, context, Boolean.FALSE);
// use string
context = genContext(
KeyValue.c("a", "4"),
KeyValue.c("b", "5"),
KeyValue.c("c", "6"),
KeyValue.c("d", "1")
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_orTrue() throws Exception {
Expression expression = genExp(orExpression);
// first
EvaluationContext context = genContext(
KeyValue.c("a", 3)
);
eval(expression, context, Boolean.TRUE);
// second
context = genContext(
KeyValue.c("a", 4),
KeyValue.c("b", 5)
);
eval(expression, context, Boolean.TRUE);
// third
context = genContext(
KeyValue.c("a", 4),
KeyValue.c("b", 4),
KeyValue.c("c", 6)
);
eval(expression, context, Boolean.TRUE);
// forth
context = genContext(
KeyValue.c("a", 4),
KeyValue.c("b", 4),
KeyValue.c("c", 3),
KeyValue.c("d", 2)
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_orFalse() throws Exception {
Expression expression = genExp(orExpression);
// forth
EvaluationContext context = genContext(
KeyValue.c("a", 4),
KeyValue.c("b", 4),
KeyValue.c("c", 3),
KeyValue.c("d", 10)
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_inTrue() throws Exception {
Expression expression = genExp(inExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "3")
);
eval(expression, context, Boolean.TRUE);
context = genContext(
KeyValue.c("a", "4")
);
eval(expression, context, Boolean.TRUE);
context = genContext(
KeyValue.c("a", "5")
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_inFalse() throws Exception {
Expression expression = genExp(inExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "8")
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_notInTrue() throws Exception {
Expression expression = genExp(notInExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "8")
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_notInFalse() throws Exception {
Expression expression = genExp(notInExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "3")
);
eval(expression, context, Boolean.FALSE);
context = genContext(
KeyValue.c("a", "4")
);
eval(expression, context, Boolean.FALSE);
context = genContext(
KeyValue.c("a", "5")
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_betweenTrue() throws Exception {
Expression expression = genExp(betweenExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "2")
);
eval(expression, context, Boolean.TRUE);
context = genContext(
KeyValue.c("a", "10")
);
eval(expression, context, Boolean.TRUE);
context = genContext(
KeyValue.c("a", "3")
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_betweenFalse() throws Exception {
Expression expression = genExp(betweenExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "1")
);
eval(expression, context, Boolean.FALSE);
context = genContext(
KeyValue.c("a", "11")
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_notBetweenTrue() throws Exception {
Expression expression = genExp(notBetweenExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "1")
);
eval(expression, context, Boolean.TRUE);
context = genContext(
KeyValue.c("a", "11")
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_notBetweenFalse() throws Exception {
Expression expression = genExp(notBetweenExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "2")
);
eval(expression, context, Boolean.FALSE);
context = genContext(
KeyValue.c("a", "10")
);
eval(expression, context, Boolean.FALSE);
context = genContext(
KeyValue.c("a", "3")
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_isNullTrue() throws Exception {
Expression expression = genExp(isNullExpression);
EvaluationContext context = genContext(
KeyValue.c("abc", "2")
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_isNullFalse() throws Exception {
Expression expression = genExp(isNullExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "2")
);
eval(expression, context, Boolean.FALSE);
}
@Test
public void testEvaluate_isNotNullTrue() throws Exception {
Expression expression = genExp(isNotNullExpression);
EvaluationContext context = genContext(
KeyValue.c("a", "2")
);
eval(expression, context, Boolean.TRUE);
}
@Test
public void testEvaluate_isNotNullFalse() throws Exception {
Expression expression = genExp(isNotNullExpression);
EvaluationContext context = genContext(
KeyValue.c("abc", "2")
);
eval(expression, context, Boolean.FALSE);
}
protected void eval(Expression expression, EvaluationContext context, Boolean result) throws Exception {
Object ret = expression.evaluate(context);
if (ret == null || !(ret instanceof Boolean)) {
assertThat(result).isFalse();
} else {
assertThat(result).isEqualTo(ret);
}
}
protected EvaluationContext genContext(KeyValue... keyValues) {
if (keyValues == null || keyValues.length < 1) {
return new PropertyContext();
}
PropertyContext context = new PropertyContext();
for (KeyValue keyValue : keyValues) {
context.properties.put(keyValue.key, keyValue.value);
}
return context;
}
protected Expression genExp(String exp) {
Expression expression = null;
try {
expression = SelectorParser.parse(exp);
assertThat(expression).isNotNull();
} catch (MQFilterException e) {
e.printStackTrace();
assertThat(Boolean.FALSE).isTrue();
}
return expression;
}
static
|
ExpressionTest
|
java
|
quarkusio__quarkus
|
integration-tests/reactive-messaging-pulsar/src/main/java/io/quarkus/it/pulsar/PulsarEndpoint.java
|
{
"start": 231,
"end": 455
}
|
class ____ {
@Inject
PulsarReceivers receivers;
@GET
@Path("/fruits")
@Produces(MediaType.APPLICATION_JSON)
public List<String> getFruits() {
return receivers.getFruits();
}
}
|
PulsarEndpoint
|
java
|
playframework__playframework
|
documentation/manual/working/javaGuide/main/async/code/javaguide/async/JavaWebSockets.java
|
{
"start": 3228,
"end": 3478
}
|
class
____ WebSocket socket() {
return WebSocket.json(InEvent.class)
.accept(
request -> ActorFlow.actorRef(MyWebSocketActor::props, actorSystem, materializer));
}
// #actor-json-class
}
public static
|
public
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/utils/MlStringsTests.java
|
{
"start": 677,
"end": 3942
}
|
class ____ extends ESTestCase {
public static final String[] SOME_INVALID_CHARS = {
"%",
" ",
"!",
"@",
"#",
"$",
"^",
"&",
"*",
"(",
")",
"+",
"=",
"{",
"}",
"[",
"]",
"|",
"\\",
":",
";",
"\"",
"'",
"<",
">",
",",
"?",
"/",
"~" };
public void testDoubleQuoteIfNotAlphaNumeric() {
assertEquals("foo2", MlStrings.doubleQuoteIfNotAlphaNumeric("foo2"));
assertEquals("\"fo o\"", MlStrings.doubleQuoteIfNotAlphaNumeric("fo o"));
assertEquals("\" \"", MlStrings.doubleQuoteIfNotAlphaNumeric(" "));
assertEquals("\"ba\\\"r\\\"\"", MlStrings.doubleQuoteIfNotAlphaNumeric("ba\"r\""));
}
public void testIsValidId() {
assertThat(MlStrings.isValidId("1_-.a"), is(true));
assertThat(MlStrings.isValidId("b.-_3"), is(true));
assertThat(MlStrings.isValidId("a-b.c_d"), is(true));
assertThat(MlStrings.isValidId("1_-.a#"), is(false));
assertThat(MlStrings.isValidId("a1_-."), is(false));
assertThat(MlStrings.isValidId("-.a1_"), is(false));
assertThat(MlStrings.isValidId(".a1_-"), is(false));
assertThat(MlStrings.isValidId("_-.a1"), is(false));
assertThat(MlStrings.isValidId("A"), is(false));
assertThat(MlStrings.isValidId("!afafd"), is(false));
assertThat(MlStrings.isValidId("_all"), is(false));
}
public void testGetParentField() {
assertThat(MlStrings.getParentField(null), is(nullValue()));
assertThat(MlStrings.getParentField("foo"), equalTo("foo"));
assertThat(MlStrings.getParentField("foo.bar"), equalTo("foo"));
assertThat(MlStrings.getParentField("x.y.z"), equalTo("x.y"));
}
public void testHasValidLengthForId() {
assertThat(MlStrings.hasValidLengthForId(randomAlphaOfLength(64)), is(true));
assertThat(MlStrings.hasValidLengthForId(randomAlphaOfLength(65)), is(false));
}
public void testFindMatching_GivenEmptyItems() {
assertThat(MlStrings.findMatching(new String[0], Collections.emptySet()), is(empty()));
}
public void testFindMatching_GivenAllPattern() {
assertThat(MlStrings.findMatching(new String[] { "_all" }, new HashSet<>(Arrays.asList("a", "b"))), contains("a", "b"));
}
public void testFindMatching_GivenWildcardPattern() {
assertThat(MlStrings.findMatching(new String[] { "*" }, new HashSet<>(Arrays.asList("a", "b"))), contains("a", "b"));
}
public void testFindMatching_GivenMixedPatterns() {
assertThat(
MlStrings.findMatching(
new String[] { "concrete", "wild-*" },
new HashSet<>(Arrays.asList("a", "concrete", "con*", "wild-1", "wild-2"))
),
contains("concrete", "wild-1", "wild-2")
);
}
public void testFindMatching_GivenItemMatchedByTwoPatterns() {
Set<String> matching = MlStrings.findMatching(new String[] { "a*", "ab*" }, new HashSet<>(Collections.singletonList("abc")));
assertThat(matching, contains("abc"));
}
}
|
MlStringsTests
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/resource/ExponentialDelay.java
|
{
"start": 1648,
"end": 3402
}
|
class ____ extends Delay {
private final Duration lower;
private final Duration upper;
private final int powersOf;
private final TimeUnit targetTimeUnit;
ExponentialDelay(Duration lower, Duration upper, int powersOf, TimeUnit targetTimeUnit) {
this.lower = lower;
this.upper = upper;
this.powersOf = powersOf;
this.targetTimeUnit = targetTimeUnit;
}
@Override
public Duration createDelay(long attempt) {
long delay;
if (attempt <= 0) { // safeguard against underflow
delay = 0;
} else if (powersOf == 2) {
delay = calculatePowerOfTwo(attempt);
} else {
delay = calculateAlternatePower(attempt);
}
return applyBounds(Duration.ofNanos(targetTimeUnit.toNanos(delay)));
}
/**
* Apply bounds to the given {@code delay}.
*
* @param delay the delay
* @return the delay normalized to its lower and upper bounds.
*/
protected Duration applyBounds(Duration delay) {
return applyBounds(delay, lower, upper);
}
private long calculateAlternatePower(long attempt) {
// round will cap at Long.MAX_VALUE and pow should prevent overflows
double step = Math.pow(powersOf, attempt - 1); // attempt > 0
return Math.round(step);
}
// fastpath with bitwise operator
protected static long calculatePowerOfTwo(long attempt) {
if (attempt <= 0) { // safeguard against underflow
return 0L;
} else if (attempt >= 63) { // safeguard against overflow in the bitshift operation
return Long.MAX_VALUE - 1;
} else {
return 1L << (attempt - 1);
}
}
}
|
ExponentialDelay
|
java
|
quarkusio__quarkus
|
extensions/smallrye-reactive-messaging/runtime/src/main/java/io/quarkus/smallrye/reactivemessaging/runtime/ContextualEmitterFactory.java
|
{
"start": 721,
"end": 1425
}
|
class ____ implements EmitterFactory<ContextualEmitterImpl<Object>> {
@Inject
ChannelRegistry channelRegistry;
@Override
public ContextualEmitterImpl<Object> createEmitter(EmitterConfiguration emitterConfiguration, long l) {
return new ContextualEmitterImpl<>(emitterConfiguration, l);
}
@Produces
@Typed(ContextualEmitter.class)
@Channel("") // Stream name is ignored during type-safe resolution
<T> ContextualEmitter<T> produceEmitter(InjectionPoint injectionPoint) {
String channelName = ChannelProducer.getChannelName(injectionPoint);
return channelRegistry.getEmitter(channelName, ContextualEmitter.class);
}
}
|
ContextualEmitterFactory
|
java
|
grpc__grpc-java
|
examples/example-debug/src/main/java/io/grpc/examples/debug/HostnameGreeter.java
|
{
"start": 1107,
"end": 2574
}
|
class ____ extends GreeterGrpc.GreeterImplBase {
private static final Logger logger = Logger.getLogger(HostnameGreeter.class.getName());
private AtomicInteger callCount = new AtomicInteger();
private final String serverName;
public HostnameGreeter(String serverName) {
if (serverName == null) {
serverName = determineHostname();
}
this.serverName = serverName;
}
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
int curCount = callCount.incrementAndGet();
HelloReply reply = HelloReply.newBuilder()
.setMessage(String.format("Hello %s, from %s. You are requester number %d.",
req.getName(), serverName, curCount))
.build();
// Add a pause so that there is time to run debug commands
try {
int sleep_interval = (curCount % 10) * 100; // 0 - 1 second
Thread.sleep(sleep_interval);
} catch (InterruptedException e) {
responseObserver.onError(e);
}
// Send the response
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
private static String determineHostname() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (IOException ex) {
logger.log(Level.INFO, "Failed to determine hostname. Will generate one", ex);
}
// Strange. Well, let's make an identifier for ourselves.
return "generated-" + new Random().nextInt();
}
}
|
HostnameGreeter
|
java
|
spring-projects__spring-boot
|
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/TaskExecutionProperties.java
|
{
"start": 5168,
"end": 5639
}
|
class ____ {
/**
* Whether to accept further tasks after the application context close phase
* has begun.
*/
private boolean acceptTasksAfterContextClose;
public boolean isAcceptTasksAfterContextClose() {
return this.acceptTasksAfterContextClose;
}
public void setAcceptTasksAfterContextClose(boolean acceptTasksAfterContextClose) {
this.acceptTasksAfterContextClose = acceptTasksAfterContextClose;
}
}
}
public static
|
Shutdown
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/api/common/ArchivedExecutionConfig.java
|
{
"start": 1096,
"end": 1198
}
|
interface ____ having to keep the classloader around after job
* completion.
*/
@Internal
public
|
without
|
java
|
spring-projects__spring-boot
|
module/spring-boot-mail/src/main/java/org/springframework/boot/mail/autoconfigure/MailSenderAutoConfiguration.java
|
{
"start": 2435,
"end": 2521
}
|
class ____ {
}
@ConditionalOnProperty("spring.mail.jndi-name")
static
|
HostProperty
|
java
|
google__dagger
|
javatests/dagger/functional/nullables/NullabilityTest.java
|
{
"start": 1110,
"end": 1328
}
|
interface ____ {
@Nullable String string();
Number number();
Provider<String> stringProvider();
Provider<Number> numberProvider();
}
@Component(modules = NullModule.class)
|
NullComponentWithDependency
|
java
|
netty__netty
|
handler/src/main/java/io/netty/handler/ssl/ApplicationProtocolNegotiationHandler.java
|
{
"start": 1475,
"end": 1968
}
|
class ____ extends {@link ChannelInitializer}<{@link Channel}> {
* private final {@link SslContext} sslCtx;
*
* public MyInitializer({@link SslContext} sslCtx) {
* this.sslCtx = sslCtx;
* }
*
* protected void initChannel({@link Channel} ch) {
* {@link ChannelPipeline} p = ch.pipeline();
* p.addLast(sslCtx.newHandler(...)); // Adds {@link SslHandler}
* p.addLast(new MyNegotiationHandler());
* }
* }
*
* public
|
MyInitializer
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/params/support/AnnotationConsumerInitializerTests.java
|
{
"start": 6145,
"end": 6527
}
|
class ____
extends AnnotationBasedArgumentConverter<JavaTimeConversionPattern> {
@Nullable
JavaTimeConversionPattern annotation;
@Override
protected @Nullable Object convert(@Nullable Object source, Class<?> targetType,
JavaTimeConversionPattern annotation) {
this.annotation = annotation;
return null;
}
}
private static
|
SomeAnnotationBasedArgumentConverter
|
java
|
quarkusio__quarkus
|
integration-tests/gradle/src/test/java/io/quarkus/gradle/SpringDependencyManagementTest.java
|
{
"start": 216,
"end": 731
}
|
class ____ extends QuarkusGradleWrapperTestBase {
@Test
public void testQuarkusBuildShouldWorkWithSpringDependencyManagement()
throws IOException, URISyntaxException, InterruptedException {
final File projectDir = getProjectDir("spring-dependency-plugin-project");
final BuildResult result = runGradleWrapper(projectDir, "clean", "quarkusBuild");
assertThat(BuildResult.isSuccessful(result.getTasks().get(":quarkusBuild"))).isTrue();
}
}
|
SpringDependencyManagementTest
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/error/ShouldBeBase64.java
|
{
"start": 820,
"end": 1294
}
|
class ____ extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldBeBase64}</code>.
* @param actual the actual value in the failed assertion.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldBeBase64(String actual) {
return new ShouldBeBase64(actual);
}
private ShouldBeBase64(String actual) {
super("%nExpecting %s to be a valid Base64 encoded string", actual);
}
}
|
ShouldBeBase64
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ClassCanBeStaticTest.java
|
{
"start": 3363,
"end": 3931
}
|
class ____ {
int localMethod() {
return outerInterMethod();
}
}
}
}\
""")
.setArgs("--release", "11")
.doTest();
}
@Test
public void positiveCase1() {
compilationHelper
.addSourceLines(
"ClassCanBeStaticPositiveCase1.java",
"""
package com.google.errorprone.bugpatterns.testdata;
/**
* @author alexloh@google.com (Alex Loh)
*/
public
|
Inner8
|
java
|
spring-projects__spring-boot
|
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java
|
{
"start": 3052,
"end": 3217
}
|
class ____ {
@Bean
String bar() {
return "bar";
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnExpression("true")
static
|
MissingConfiguration
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/logging/LogControllerFactory.java
|
{
"start": 1080,
"end": 2269
}
|
class ____ {
private static final Logger LOG = LoggerFactory.getLogger(LogControllerFactory.class);
/**
* Log once: when there are logging issues, logging lots just
* makes it worse.
*/
private static final LogExactlyOnce LOG_ONCE = new LogExactlyOnce(LOG);
/**
* Class name of log controller implementation to be loaded
* through reflection.
* {@value}.
*/
private static final String LOG4J_CONTROLLER =
"org.apache.hadoop.fs.s3a.impl.logging.Log4JController";
private LogControllerFactory() {
}
/**
* Create a controller. Failure to load is logged at debug
* and null is returned.
* @param classname name of controller to load and create.
* @return the instantiated controller or null if it failed to load
*/
public static LogControl createController(String classname) {
try {
Class<?> clazz = Class.forName(classname);
return (LogControl) clazz.newInstance();
} catch (Exception e) {
LOG_ONCE.debug("Failed to create controller {}: {}", classname, e, e);
return null;
}
}
/**
* Create a Log4J controller.
* @return the instantiated controller or null if the
|
LogControllerFactory
|
java
|
quarkusio__quarkus
|
extensions/smallrye-fault-tolerance/runtime/src/main/java/io/quarkus/smallrye/faulttolerance/runtime/config/SmallRyeFaultToleranceConfig.java
|
{
"start": 6919,
"end": 7141
}
|
class ____ the {@link BeforeRetryHandler} to call before retrying.
*
* @see BeforeRetry#value()
*/
Optional<Class<? extends BeforeRetryHandler>> value();
}
|
of
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/spi/ResteasyReactiveClientRequestFilter.java
|
{
"start": 198,
"end": 287
}
|
interface ____ by client request filters used by REST Client Reactive.
*/
public
|
implemented
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestTopCLI.java
|
{
"start": 1769,
"end": 1801
}
|
class ____ TopCli.
*
*/
public
|
for
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java
|
{
"start": 75018,
"end": 75067
}
|
class ____ extends Fields<String> {
}
|
TypedFields
|
java
|
playframework__playframework
|
documentation/manual/working/javaGuide/main/tests/code/javaguide/tests/ControllerTest.java
|
{
"start": 507,
"end": 1243
}
|
class ____ {
@Test
public void testIndex() {
Result result = new HomeController().index();
assertEquals(OK, result.status());
assertEquals("text/html", result.contentType().get());
assertEquals("utf-8", result.charset().get());
assertTrue(contentAsString(result).contains("Welcome"));
}
// ###replace: }
// #test-controller-test
// #test-template
@Test
public void renderTemplate() {
// ###replace: Content html = views.html.index.render("Welcome to Play!");
Content html = javaguide.tests.html.index.render("Welcome to Play!");
assertEquals("text/html", html.contentType());
assertTrue(contentAsString(html).contains("Welcome to Play!"));
}
// #test-template
}
|
ControllerTest
|
java
|
apache__flink
|
flink-filesystems/flink-s3-fs-base/src/test/java/org/apache/flink/fs/s3/common/S5CmdOnMinioITCase.java
|
{
"start": 12099,
"end": 14906
}
|
class ____ extends RichSourceFunction<Record> implements CheckpointedFunction {
public static final int FIRST_KEY = 1;
public static final int SECOND_KEY = 2;
public static final int LAST_EMITTED_VALUE = 10;
private static final int FAIL_AFTER_VALUE = LAST_EMITTED_VALUE / 2;
private ListState<Integer> lastEmittedValueState;
private int lastEmittedValue;
private boolean isRestored = false;
private boolean emitted = false;
private volatile boolean running = true;
@Override
public void run(SourceContext ctx) throws Exception {
while (running && lastEmittedValue < LAST_EMITTED_VALUE) {
synchronized (ctx.getCheckpointLock()) {
if (!emitted) {
lastEmittedValue += 1;
ctx.collect(new Record(FIRST_KEY, lastEmittedValue));
ctx.collect(new Record(SECOND_KEY, 2 * lastEmittedValue));
emitted = true;
}
}
Thread.sleep(CHECKPOINT_INTERVAL / 20 + 1);
}
}
@Override
public void cancel() {
running = false;
}
@Override
public void snapshotState(FunctionSnapshotContext context) throws Exception {
if (!isRestored && lastEmittedValue > FAIL_AFTER_VALUE) {
throw new ExpectedTestException("Time to failover!");
}
lastEmittedValueState.update(Collections.singletonList(lastEmittedValue));
emitted = false;
}
@Override
public void initializeState(FunctionInitializationContext context) throws Exception {
lastEmittedValueState =
context.getOperatorStateStore()
.getListState(
new ListStateDescriptor<>("lastEmittedValue", Integer.class));
Iterator<Integer> lastEmittedValues = lastEmittedValueState.get().iterator();
if (lastEmittedValues.hasNext()) {
lastEmittedValue = lastEmittedValues.next();
isRestored = true;
}
checkState(!lastEmittedValues.hasNext());
}
}
private static String createS3URIWithSubPath(String... subfolders) {
return getMinioContainer().getS3UriForDefaultBucket() + createSubPath(subfolders);
}
private static String createSubPath(String... subfolders) {
final String pathSeparator = "/";
return pathSeparator + StringUtils.join(subfolders, pathSeparator);
}
private static String getS5CmdPath() {
return Paths.get(temporaryDirectory.getPath(), "s5cmd").toAbsolutePath().toString();
}
}
|
FailingSource
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/util/ClassLoaderUtil.java
|
{
"start": 1095,
"end": 1188
}
|
class ____ for the
* dynamic loading of user defined classes.
*/
@Internal
public final
|
loaders
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/anthropic/response/AnthropicChatCompletionResponseEntity.java
|
{
"start": 4736,
"end": 5233
}
|
class ____ {
private String type;
private String text;
private Builder() {}
public Builder setType(String type) {
this.type = type;
return this;
}
public Builder setText(String text) {
this.text = text;
return this;
}
public TextObject build() {
return new TextObject(type, text);
}
}
}
}
|
Builder
|
java
|
spring-projects__spring-framework
|
spring-web/src/test/java/org/springframework/http/codec/ResourceHttpMessageReaderTests.java
|
{
"start": 1497,
"end": 2680
}
|
class ____ extends AbstractLeakCheckingTests {
private final ResourceHttpMessageReader reader = new ResourceHttpMessageReader();
@Test
void readResourceAsMono() throws IOException {
String filename = "test.txt";
String body = "Test resource content";
ContentDisposition contentDisposition =
ContentDisposition.attachment().name("file").filename(filename).build();
MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
response.getHeaders().setContentDisposition(contentDisposition);
response.setBody(Mono.just(stringBuffer(body)));
Resource resource = reader.readMono(
ResolvableType.forClass(ByteArrayResource.class), response, Collections.emptyMap()).block();
assertThat(resource).isNotNull();
assertThat(resource.getFilename()).isEqualTo(filename);
assertThat(resource.getInputStream()).hasContent(body);
}
private DataBuffer stringBuffer(String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = this.bufferFactory.allocateBuffer(bytes.length);
buffer.write(bytes);
return buffer;
}
}
|
ResourceHttpMessageReaderTests
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/functional/ConsumerRaisingIOE.java
|
{
"start": 1019,
"end": 1501
}
|
interface ____<T> {
/**
* Process the argument.
* @param t type
* @throws IOException if needed
*/
void accept(T t) throws IOException;
/**
* after calling {@link #accept(Object)},
* invoke the next consumer in the chain.
* @param next next consumer
* @return the chain.
*/
default ConsumerRaisingIOE<T> andThen(
ConsumerRaisingIOE<? super T> next) {
return (T t) -> {
accept(t);
next.accept(t);
};
}
}
|
ConsumerRaisingIOE
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/conditional/ClampMaxIntegerEvaluator.java
|
{
"start": 1090,
"end": 4884
}
|
class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(ClampMaxIntegerEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator field;
private final EvalOperator.ExpressionEvaluator max;
private final DriverContext driverContext;
private Warnings warnings;
public ClampMaxIntegerEvaluator(Source source, EvalOperator.ExpressionEvaluator field,
EvalOperator.ExpressionEvaluator max, DriverContext driverContext) {
this.source = source;
this.field = field;
this.max = max;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (IntBlock fieldBlock = (IntBlock) field.eval(page)) {
try (IntBlock maxBlock = (IntBlock) max.eval(page)) {
IntVector fieldVector = fieldBlock.asVector();
if (fieldVector == null) {
return eval(page.getPositionCount(), fieldBlock, maxBlock);
}
IntVector maxVector = maxBlock.asVector();
if (maxVector == null) {
return eval(page.getPositionCount(), fieldBlock, maxBlock);
}
return eval(page.getPositionCount(), fieldVector, maxVector).asBlock();
}
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += field.baseRamBytesUsed();
baseRamBytesUsed += max.baseRamBytesUsed();
return baseRamBytesUsed;
}
public IntBlock eval(int positionCount, IntBlock fieldBlock, IntBlock maxBlock) {
try(IntBlock.Builder result = driverContext.blockFactory().newIntBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
switch (fieldBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
switch (maxBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
int field = fieldBlock.getInt(fieldBlock.getFirstValueIndex(p));
int max = maxBlock.getInt(maxBlock.getFirstValueIndex(p));
result.appendInt(ClampMax.process(field, max));
}
return result.build();
}
}
public IntVector eval(int positionCount, IntVector fieldVector, IntVector maxVector) {
try(IntVector.FixedBuilder result = driverContext.blockFactory().newIntVectorFixedBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
int field = fieldVector.getInt(p);
int max = maxVector.getInt(p);
result.appendInt(p, ClampMax.process(field, max));
}
return result.build();
}
}
@Override
public String toString() {
return "ClampMaxIntegerEvaluator[" + "field=" + field + ", max=" + max + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(field, max);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static
|
ClampMaxIntegerEvaluator
|
java
|
elastic__elasticsearch
|
x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkDocTests.java
|
{
"start": 1309,
"end": 8953
}
|
class ____ extends ESTestCase {
private MonitoredSystem system;
private String type;
private String id;
private long timestamp;
private long interval;
private BytesReference source;
private XContentType xContentType;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
system = randomFrom(MonitoredSystem.values());
type = randomAlphaOfLength(5);
id = randomBoolean() ? randomAlphaOfLength(10) : null;
timestamp = randomNonNegativeLong();
interval = randomNonNegativeLong();
xContentType = randomFrom(XContentType.values());
source = RandomObjects.randomSource(random(), xContentType);
}
public void testConstructorMonitoredSystemMustNotBeNull() {
expectThrows(NullPointerException.class, () -> new MonitoringBulkDoc(null, type, id, timestamp, interval, source, xContentType));
}
public void testConstructorTypeMustNotBeNull() {
expectThrows(NullPointerException.class, () -> new MonitoringBulkDoc(system, null, id, timestamp, interval, source, xContentType));
}
public void testConstructorSourceMustNotBeNull() {
expectThrows(NullPointerException.class, () -> new MonitoringBulkDoc(system, type, id, timestamp, interval, null, xContentType));
}
public void testConstructorXContentTypeMustNotBeNull() {
expectThrows(NullPointerException.class, () -> new MonitoringBulkDoc(system, type, id, timestamp, interval, source, null));
}
public void testConstructor() {
final MonitoringBulkDoc document = new MonitoringBulkDoc(system, type, id, timestamp, interval, source, xContentType);
assertThat(document.getSystem(), equalTo(system));
assertThat(document.getType(), equalTo(type));
assertThat(document.getId(), equalTo(id));
assertThat(document.getTimestamp(), equalTo(timestamp));
assertThat(document.getIntervalMillis(), equalTo(interval));
assertThat(document.getSource(), equalBytes(source));
assertThat(document.getXContentType(), equalTo(xContentType));
}
public void testEqualsAndHashcode() {
final EqualsHashCodeTestUtils.CopyFunction<MonitoringBulkDoc> copy = doc -> new MonitoringBulkDoc(
doc.getSystem(),
doc.getType(),
doc.getId(),
doc.getTimestamp(),
doc.getIntervalMillis(),
doc.getSource(),
doc.getXContentType()
);
final List<EqualsHashCodeTestUtils.MutateFunction<MonitoringBulkDoc>> mutations = new ArrayList<>();
mutations.add(doc -> {
MonitoredSystem randomSystem;
do {
randomSystem = randomFrom(MonitoredSystem.values());
} while (randomSystem == doc.getSystem());
return new MonitoringBulkDoc(
randomSystem,
doc.getType(),
doc.getId(),
doc.getTimestamp(),
doc.getIntervalMillis(),
doc.getSource(),
doc.getXContentType()
);
});
mutations.add(doc -> {
String randomType;
do {
randomType = randomAlphaOfLength(5);
} while (randomType.equals(doc.getType()));
return new MonitoringBulkDoc(
doc.getSystem(),
randomType,
doc.getId(),
doc.getTimestamp(),
doc.getIntervalMillis(),
doc.getSource(),
doc.getXContentType()
);
});
mutations.add(doc -> {
String randomId;
do {
randomId = randomAlphaOfLength(10);
} while (randomId.equals(doc.getId()));
return new MonitoringBulkDoc(
doc.getSystem(),
doc.getType(),
randomId,
doc.getTimestamp(),
doc.getIntervalMillis(),
doc.getSource(),
doc.getXContentType()
);
});
mutations.add(doc -> {
long randomTimestamp;
do {
randomTimestamp = randomNonNegativeLong();
} while (randomTimestamp == doc.getTimestamp());
return new MonitoringBulkDoc(
doc.getSystem(),
doc.getType(),
doc.getId(),
randomTimestamp,
doc.getIntervalMillis(),
doc.getSource(),
doc.getXContentType()
);
});
mutations.add(doc -> {
long randomInterval;
do {
randomInterval = randomNonNegativeLong();
} while (randomInterval == doc.getIntervalMillis());
return new MonitoringBulkDoc(
doc.getSystem(),
doc.getType(),
doc.getId(),
doc.getTimestamp(),
randomInterval,
doc.getSource(),
doc.getXContentType()
);
});
mutations.add(doc -> {
final BytesReference randomSource = RandomObjects.randomSource(random(), doc.getXContentType());
return new MonitoringBulkDoc(
doc.getSystem(),
doc.getType(),
doc.getId(),
doc.getTimestamp(),
doc.getIntervalMillis(),
randomSource,
doc.getXContentType()
);
});
mutations.add(doc -> {
XContentType randomXContentType;
do {
randomXContentType = randomFrom(XContentType.values());
} while (randomXContentType == doc.getXContentType());
return new MonitoringBulkDoc(
doc.getSystem(),
doc.getType(),
doc.getId(),
doc.getTimestamp(),
doc.getIntervalMillis(),
doc.getSource(),
randomXContentType
);
});
final MonitoringBulkDoc document = new MonitoringBulkDoc(system, type, id, timestamp, interval, source, xContentType);
checkEqualsAndHashCode(document, copy, randomFrom(mutations));
}
public void testSerialization() throws IOException {
final NamedWriteableRegistry registry = new NamedWriteableRegistry(emptyList());
final int iterations = randomIntBetween(5, 50);
for (int i = 0; i < iterations; i++) {
final MonitoringBulkDoc original = randomMonitoringBulkDoc(random());
final MonitoringBulkDoc deserialized = copyWriteable(original, registry, MonitoringBulkDoc::new);
assertEquals(original, deserialized);
assertEquals(original.hashCode(), deserialized.hashCode());
assertNotSame(original, deserialized);
}
}
/**
* Test that we allow strings to be "" because Logstash 5.2 - 5.3 would submit empty _id values for time-based documents
*/
public void testEmptyIdBecomesNull() {
final String randomId = randomFrom("", null, randomAlphaOfLength(5));
final MonitoringBulkDoc doc = new MonitoringBulkDoc(
MonitoredSystem.ES,
"_type",
randomId,
1L,
2L,
BytesArray.EMPTY,
XContentType.JSON
);
if (Strings.isNullOrEmpty(randomId)) {
assertNull(doc.getId());
} else {
assertSame(randomId, doc.getId());
}
}
}
|
MonitoringBulkDocTests
|
java
|
quarkusio__quarkus
|
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/QueryStringAttribute.java
|
{
"start": 1980,
"end": 2921
}
|
class ____ implements ExchangeAttributeBuilder {
@Override
public String name() {
return "Query String";
}
@Override
public ExchangeAttribute build(final String token) {
if (token.equals(QUERY_STRING) || token.equals(QUERY_STRING_SHORT)) {
return QueryStringAttribute.INSTANCE;
} else if (token.equals(BARE_QUERY_STRING)) {
return QueryStringAttribute.BARE_INSTANCE;
} else if (token.equals(ORIGINAL_QUERY_STRING) || token.equals(ORIGINAL_QUERY_STRING_SHORT)) {
return QueryStringAttribute.INSTANCE_ORIGINAL_REQUEST;
} else if (token.equals(ORIGINAL_BARE_QUERY_STRING)) {
return QueryStringAttribute.BARE_INSTANCE_ORIGINAL_REQUEST;
}
return null;
}
@Override
public int priority() {
return 0;
}
}
}
|
Builder
|
java
|
apache__logging-log4j2
|
log4j-api/src/main/java/org/apache/logging/log4j/message/FlowMessage.java
|
{
"start": 895,
"end": 1240
}
|
interface ____ extends Message {
/**
* The message text like "Enter" or "Exit" used to prefix the actual Message.
*
* @return message text used to prefix the actual Message.
*/
String getText();
/**
* The wrapped message
*
* @return the wrapped message
*/
Message getMessage();
}
|
FlowMessage
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3ListRequest.java
|
{
"start": 1061,
"end": 2717
}
|
class ____ {
/**
* Format for the toString() method: {@value}.
*/
private static final String DESCRIPTION
= "List %s:/%s delimiter=%s keys=%d requester pays=%s";
private final ListObjectsRequest v1Request;
private final ListObjectsV2Request v2Request;
private S3ListRequest(ListObjectsRequest v1, ListObjectsV2Request v2) {
v1Request = v1;
v2Request = v2;
}
/**
* Restricted constructors to ensure v1 or v2, not both.
* @param request v1 request
* @return new list request container
*/
public static S3ListRequest v1(ListObjectsRequest request) {
return new S3ListRequest(request, null);
}
/**
* Restricted constructors to ensure v1 or v2, not both.
* @param request v2 request
* @return new list request container
*/
public static S3ListRequest v2(ListObjectsV2Request request) {
return new S3ListRequest(null, request);
}
/**
* Is this a v1 API request or v2?
* @return true if v1, false if v2
*/
public boolean isV1() {
return v1Request != null;
}
public ListObjectsRequest getV1() {
return v1Request;
}
public ListObjectsV2Request getV2() {
return v2Request;
}
@Override
public String toString() {
if (isV1()) {
return String.format(DESCRIPTION,
v1Request.bucket(), v1Request.prefix(),
v1Request.delimiter(), v1Request.maxKeys(),
v1Request.requestPayerAsString());
} else {
return String.format(DESCRIPTION,
v2Request.bucket(), v2Request.prefix(),
v2Request.delimiter(), v2Request.maxKeys(),
v2Request.requestPayerAsString());
}
}
}
|
S3ListRequest
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/BlockReportTestBase.java
|
{
"start": 3695,
"end": 4042
}
|
class ____ simulating a variety of situations
* when blocks are being intentionally corrupted, unexpectedly modified,
* and so on before a block report is happening.
*
* By overriding {@link #sendBlockReports}, derived classes can test
* different variations of how block reports are split across storages
* and messages.
*/
public abstract
|
for
|
java
|
apache__camel
|
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/JcacheComponentBuilderFactory.java
|
{
"start": 3718,
"end": 8121
}
|
class ____ of the
* javax.cache.spi.CachingProvider.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param cachingProvider the value to set
* @return the dsl builder
*/
default JcacheComponentBuilder cachingProvider(java.lang.String cachingProvider) {
doSetProperty("cachingProvider", cachingProvider);
return this;
}
/**
* An implementation specific URI for the CacheManager.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param configurationUri the value to set
* @return the dsl builder
*/
default JcacheComponentBuilder configurationUri(java.lang.String configurationUri) {
doSetProperty("configurationUri", configurationUri);
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 is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default JcacheComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default JcacheComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default JcacheComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
|
name
|
java
|
micronaut-projects__micronaut-core
|
json-core/src/main/java/io/micronaut/json/JsonConfiguration.java
|
{
"start": 689,
"end": 803
}
|
interface ____ application-level json configuration.
*
* @author Jonas Konrad
* @since 3.1
*/
@Internal
public
|
for
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/crypto/key/KeyProvider.java
|
{
"start": 10960,
"end": 23262
}
|
class ____ {
private String cipher;
private int bitLength;
private String description;
private Map<String, String> attributes;
public Options(Configuration conf) {
cipher = conf.get(DEFAULT_CIPHER_NAME, DEFAULT_CIPHER);
bitLength = conf.getInt(DEFAULT_BITLENGTH_NAME, DEFAULT_BITLENGTH);
}
public Options setCipher(String cipher) {
this.cipher = cipher;
return this;
}
public Options setBitLength(int bitLength) {
this.bitLength = bitLength;
return this;
}
public Options setDescription(String description) {
this.description = description;
return this;
}
public Options setAttributes(Map<String, String> attributes) {
if (attributes != null) {
if (attributes.containsKey(null)) {
throw new IllegalArgumentException("attributes cannot have a NULL key");
}
this.attributes = new HashMap<String, String>(attributes);
}
return this;
}
public String getCipher() {
return cipher;
}
public int getBitLength() {
return bitLength;
}
public String getDescription() {
return description;
}
public Map<String, String> getAttributes() {
return (attributes == null) ? Collections.emptyMap() : attributes;
}
@Override
public String toString() {
return "Options{" +
"cipher='" + cipher + '\'' +
", bitLength=" + bitLength +
", description='" + description + '\'' +
", attributes=" + attributes +
'}';
}
}
/**
* Constructor.
*
* @param conf configuration for the provider
*/
public KeyProvider(Configuration conf) {
this.conf = new Configuration(conf);
// Added for HADOOP-15473. Configured serialFilter property fixes
// java.security.UnrecoverableKeyException in JDK 8u171.
if(System.getProperty(JCEKS_KEY_SERIAL_FILTER) == null) {
String serialFilter =
conf.get(HADOOP_SECURITY_CRYPTO_JCEKS_KEY_SERIALFILTER,
JCEKS_KEY_SERIALFILTER_DEFAULT);
System.setProperty(JCEKS_KEY_SERIAL_FILTER, serialFilter);
}
CryptoUtils.getJceProvider(conf);
}
/**
* Return the provider configuration.
*
* @return the provider configuration
*/
public Configuration getConf() {
return conf;
}
/**
* A helper function to create an options object.
* @param conf the configuration to use
* @return a new options object
*/
public static Options options(Configuration conf) {
return new Options(conf);
}
/**
* Indicates whether this provider represents a store
* that is intended for transient use - such as the UserProvider
* is. These providers are generally used to provide access to
* keying material rather than for long term storage.
* @return true if transient, false otherwise
*/
public boolean isTransient() {
return false;
}
/**
* Get the key material for a specific version of the key. This method is used
* when decrypting data.
* @param versionName the name of a specific version of the key
* @return the key material
* @throws IOException raised on errors performing I/O.
*/
public abstract KeyVersion getKeyVersion(String versionName
) throws IOException;
/**
* Get the key names for all keys.
* @return the list of key names
* @throws IOException raised on errors performing I/O.
*/
public abstract List<String> getKeys() throws IOException;
/**
* Get key metadata in bulk.
* @param names the names of the keys to get
* @throws IOException raised on errors performing I/O.
* @return Metadata Array.
*/
public Metadata[] getKeysMetadata(String... names) throws IOException {
Metadata[] result = new Metadata[names.length];
for (int i=0; i < names.length; ++i) {
result[i] = getMetadata(names[i]);
}
return result;
}
/**
* Get the key material for all versions of a specific key name.
*
* @param name the base name of the key.
* @return the list of key material
* @throws IOException raised on errors performing I/O.
*/
public abstract List<KeyVersion> getKeyVersions(String name) throws IOException;
/**
* Get the current version of the key, which should be used for encrypting new
* data.
* @param name the base name of the key
* @return the version name of the current version of the key or null if the
* key version doesn't exist
* @throws IOException raised on errors performing I/O.
*/
public KeyVersion getCurrentKey(String name) throws IOException {
Metadata meta = getMetadata(name);
if (meta == null) {
return null;
}
return getKeyVersion(buildVersionName(name, meta.getVersions() - 1));
}
/**
* Get metadata about the key.
* @param name the basename of the key
* @return the key's metadata or null if the key doesn't exist
* @throws IOException raised on errors performing I/O.
*/
public abstract Metadata getMetadata(String name) throws IOException;
/**
* Create a new key. The given key must not already exist.
* @param name the base name of the key
* @param material the key material for the first version of the key.
* @param options the options for the new key.
* @return the version name of the first version of the key.
* @throws IOException raised on errors performing I/O.
*/
public abstract KeyVersion createKey(String name, byte[] material,
Options options) throws IOException;
/**
* Get the algorithm from the cipher.
*
* @return the algorithm name
*/
private String getAlgorithm(String cipher) {
int slash = cipher.indexOf('/');
if (slash == -1) {
return cipher;
} else {
return cipher.substring(0, slash);
}
}
/**
* Generates a key material.
*
* @param size length of the key.
* @param algorithm algorithm to use for generating the key.
* @return the generated key.
* @throws NoSuchAlgorithmException no such algorithm exception.
*/
protected byte[] generateKey(int size, String algorithm)
throws NoSuchAlgorithmException {
algorithm = getAlgorithm(algorithm);
KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
keyGenerator.init(size);
byte[] key = keyGenerator.generateKey().getEncoded();
return key;
}
/**
* Create a new key generating the material for it.
* The given key must not already exist.
* <p>
* This implementation generates the key material and calls the
* {@link #createKey(String, byte[], Options)} method.
*
* @param name the base name of the key
* @param options the options for the new key.
* @return the version name of the first version of the key.
* @throws IOException raised on errors performing I/O.
* @throws NoSuchAlgorithmException no such algorithm exception.
*/
public KeyVersion createKey(String name, Options options)
throws NoSuchAlgorithmException, IOException {
byte[] material = generateKey(options.getBitLength(), options.getCipher());
return createKey(name, material, options);
}
/**
* Delete the given key.
* @param name the name of the key to delete
* @throws IOException raised on errors performing I/O.
*/
public abstract void deleteKey(String name) throws IOException;
/**
* Roll a new version of the given key.
* @param name the basename of the key
* @param material the new key material
* @return the name of the new version of the key
* @throws IOException raised on errors performing I/O.
*/
public abstract KeyVersion rollNewVersion(String name,
byte[] material
) throws IOException;
/**
* Can be used by implementing classes to close any resources
* that require closing
*/
public void close() throws IOException {
// NOP
}
/**
* Roll a new version of the given key generating the material for it.
* <p>
* This implementation generates the key material and calls the
* {@link #rollNewVersion(String, byte[])} method.
*
* @param name the basename of the key
* @return the name of the new version of the key
* @throws IOException raised on errors performing I/O.
* @throws NoSuchAlgorithmException This exception is thrown when a particular
* cryptographic algorithm is requested
* but is not available in the environment.
*/
public KeyVersion rollNewVersion(String name) throws NoSuchAlgorithmException,
IOException {
Metadata meta = getMetadata(name);
if (meta == null) {
throw new IOException("Can't find Metadata for key " + name);
}
byte[] material = generateKey(meta.getBitLength(), meta.getCipher());
return rollNewVersion(name, material);
}
/**
* Can be used by implementing classes to invalidate the caches. This could be
* used after rollNewVersion to provide a strong guarantee to return the new
* version of the given key.
*
* @param name the basename of the key
* @throws IOException raised on errors performing I/O.
*/
public void invalidateCache(String name) throws IOException {
// NOP
}
/**
* Ensures that any changes to the keys are written to persistent store.
* @throws IOException raised on errors performing I/O.
*/
public abstract void flush() throws IOException;
/**
* Split the versionName in to a base name. Converts "/aaa/bbb@3" to
* "/aaa/bbb".
* @param versionName the version name to split
* @return the base name of the key
* @throws IOException raised on errors performing I/O.
*/
public static String getBaseName(String versionName) throws IOException {
Objects.requireNonNull(versionName, "VersionName cannot be null");
int div = versionName.lastIndexOf('@');
if (div == -1) {
throw new IOException("No version in key path " + versionName);
}
return versionName.substring(0, div);
}
/**
* Build a version string from a basename and version number. Converts
* "/aaa/bbb" and 3 to "/aaa/bbb@3".
* @param name the basename of the key
* @param version the version of the key
* @return the versionName of the key.
*/
protected static String buildVersionName(String name, int version) {
return name + "@" + version;
}
/**
* Find the provider with the given key.
*
* @param providerList the list of providers
* @param keyName the key name we are looking for.
* @return the KeyProvider that has the key
* @throws IOException raised on errors performing I/O.
*/
public static KeyProvider findProvider(List<KeyProvider> providerList,
String keyName) throws IOException {
for(KeyProvider provider: providerList) {
if (provider.getMetadata(keyName) != null) {
return provider;
}
}
throw new IOException("Can't find KeyProvider for key " + keyName);
}
/**
* Does this provider require a password? This means that a password is
* required for normal operation, and it has not been found through normal
* means. If true, the password should be provided by the caller using
* setPassword().
* @return Whether or not the provider requires a password
* @throws IOException raised on errors performing I/O.
*/
public boolean needsPassword() throws IOException {
return false;
}
/**
* If a password for the provider is needed, but is not provided, this will
* return a warning and instructions for supplying said password to the
* provider.
* @return A warning and instructions for supplying the password
*/
public String noPasswordWarning() {
return null;
}
/**
* If a password for the provider is needed, but is not provided, this will
* return an error message and instructions for supplying said password to
* the provider.
* @return An error message and instructions for supplying the password
*/
public String noPasswordError() {
return null;
}
}
|
Options
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/encoded/ClientWithPathParamAndEncodedTest.java
|
{
"start": 2510,
"end": 2809
}
|
interface ____ {
@GET
@Path("/{path}")
String call(@PathParam("path") String path);
@GET
@Path("/{path}")
String callWithQuery(@PathParam("path") String path, @QueryParam("query") String query);
}
@Path("/server")
public
|
ClientWithoutEncoded
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/alternatives/AlternativesPriorityTest.java
|
{
"start": 1307,
"end": 1518
}
|
class ____ implements Supplier<String> {
@Override
public String get() {
return getClass().getName();
}
}
@Alternative
@Priority(10)
@Singleton
static
|
Bravo
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/OrderBy.java
|
{
"start": 569,
"end": 1660
}
|
class ____ extends UnaryPlan {
private final List<Order> order;
public OrderBy(Source source, LogicalPlan child, List<Order> order) {
super(source, child);
this.order = order;
}
@Override
protected NodeInfo<OrderBy> info() {
return NodeInfo.create(this, OrderBy::new, child(), order);
}
@Override
public OrderBy replaceChild(LogicalPlan newChild) {
return new OrderBy(source(), newChild, order);
}
public List<Order> order() {
return order;
}
@Override
public boolean expressionsResolved() {
return Resolvables.resolved(order);
}
@Override
public int hashCode() {
return Objects.hash(order, child());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
OrderBy other = (OrderBy) obj;
return Objects.equals(order, other.order) && Objects.equals(child(), other.child());
}
}
|
OrderBy
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/maps/Maps_assertContainsExactly_Test.java
|
{
"start": 2024,
"end": 7693
}
|
class ____ extends MapsBaseTest {
private LinkedHashMap<String, String> linkedActual;
@BeforeEach
void initLinkedHashMap() {
linkedActual = new LinkedHashMap<>(2);
linkedActual.put("name", "Yoda");
linkedActual.put("color", "green");
}
@Test
void should_fail_if_actual_is_null() {
// GIVEN
actual = null;
Entry<String, String>[] expected = array(entry("name", "Yoda"));
// WHEN
var assertionError = expectAssertionError(() -> maps.assertContainsExactly(INFO, actual, expected, null));
// THEN
then(assertionError).hasMessage(actualIsNull());
}
@Test
void should_fail_if_given_entries_array_is_null() {
// GIVEN
Entry<String, String>[] entries = null;
// WHEN/THEN
thenNullPointerException().isThrownBy(() -> maps.assertContainsExactly(INFO, linkedActual, entries, null))
.withMessage(entriesToLookForIsNull());
}
@Test
void should_fail_if_given_entries_array_is_empty() {
// GIVEN
Entry<String, String>[] expected = emptyEntries();
// WHEN
expectAssertionError(() -> maps.assertContainsExactly(INFO, actual, expected, null));
// THEN
verify(failures).failure(INFO, shouldBeEmpty(actual));
}
@Test
void should_pass_if_actual_and_entries_are_empty() {
maps.assertContainsExactly(INFO, emptyMap(), array(), null);
}
@Test
void should_pass_if_actual_contains_given_entries_in_order() {
maps.assertContainsExactly(INFO, linkedActual, array(entry("name", "Yoda"), entry("color", "green")), null);
}
@Test
void should_fail_if_actual_contains_given_entries_in_disorder() {
// WHEN
expectAssertionError(() -> maps.assertContainsExactly(INFO, linkedActual,
array(entry("color", "green"), entry("name", "Yoda")), null));
// THEN
verify(failures).failure(INFO, elementsDifferAtIndex(entry("name", "Yoda"), entry("color", "green"), 0));
}
@Test
void should_fail_if_actual_and_expected_entries_have_different_size() {
// GIVEN
Entry<String, String>[] expected = array(entry("name", "Yoda"));
// WHEN
var assertionError = expectAssertionError(() -> maps.assertContainsExactly(INFO, linkedActual, expected, null));
// THEN
then(assertionError).hasMessage(shouldHaveSameSizeAs(linkedActual, expected, linkedActual.size(), expected.length).create());
}
@Test
void should_fail_if_actual_does_not_contains_every_expected_entries_and_contains_unexpected_one() {
// GIVEN
Entry<String, String>[] expected = array(entry("name", "Yoda"), entry("color", "green"));
Map<String, String> underTest = mapOf(entry("name", "Yoda"), entry("job", "Jedi"));
// WHEN
expectAssertionError(() -> maps.assertContainsExactly(INFO, underTest, expected, null));
// THEN
verify(failures).failure(INFO, shouldContainExactly(underTest, list(expected),
set(entry("color", "green")),
set(entry("job", "Jedi"))));
}
@Test
void should_fail_if_actual_contains_entry_key_with_different_value() {
// GIVEN
Entry<String, String>[] expectedEntries = array(entry("name", "Yoda"), entry("color", "yellow"));
// WHEN
expectAssertionError(() -> maps.assertContainsExactly(INFO, actual, expectedEntries, null));
// THEN
verify(failures).failure(INFO, shouldContainExactly(actual, asList(expectedEntries),
set(entry("color", "yellow")),
set(entry("color", "green"))));
}
@Test
void should_pass_with_singleton_map_having_array_value() {
// GIVEN
Map<String, String[]> actual = singletonMap("color", array("yellow"));
Entry<String, String[]>[] expected = array(entry("color", array("yellow")));
// WHEN/THEN
maps.assertContainsExactly(INFO, actual, expected, null);
}
@Test
void should_fail_with_singleton_map_having_array_value() {
// GIVEN
Map<String, String[]> actual = singletonMap("color", array("yellow"));
Entry<String, String[]>[] expected = array(entry("color", array("green")));
// WHEN
var assertionError = expectAssertionError(() -> maps.assertContainsExactly(INFO, actual, expected, null));
// THEN
then(assertionError).hasMessage(shouldContainExactly(actual, asList(expected),
set(entry("color", array("green"))),
set(entry("color", array("yellow")))).create());
}
@Test
void should_pass_with_Properties() {
// GIVEN
Properties actual = mapOf(Properties::new, entry("name", "Yoda"), entry("job", "Jedi"));
Entry<Object, Object>[] expected = array(entry("name", "Yoda"), entry("job", "Jedi"));
// WHEN/THEN
maps.assertContainsExactly(INFO, actual, expected, null);
}
@Test
void should_fail_with_Properties() {
// GIVEN
Properties actual = mapOf(Properties::new, entry("name", "Yoda"), entry("job", "Jedi"));
Entry<Object, Object>[] expected = array(entry("name", "Yoda"), entry("color", "green"));
// WHEN
var assertionError = expectAssertionError(() -> maps.assertContainsExactly(INFO, actual, expected, null));
// THEN
then(assertionError).hasMessage(shouldContainExactly(actual, asList(expected),
set(entry("color", "green")),
set(entry("job", "Jedi"))).create());
}
}
|
Maps_assertContainsExactly_Test
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java
|
{
"start": 5520,
"end": 6279
}
|
class ____ directly against " +
"AnnotationConfigApplicationContext did not trigger component scanning as expected").isTrue();
assertThat(ctx.getBean(ConfigurableComponent.class).isFlag()).as("@Bean method overrides scanned class").isTrue();
}
@Test
void viaContextRegistration_WithComposedAnnotation() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ComposedAnnotationConfig.class);
ctx.getBean(ComposedAnnotationConfig.class);
ctx.getBean(SimpleComponent.class);
ctx.getBean(ClassWithNestedComponents.NestedComponent.class);
ctx.getBean(ClassWithNestedComponents.OtherNestedComponent.class);
assertThat(ctx.containsBeanDefinition("componentScanAnnotationIntegrationTests.ComposedAnnotationConfig")).as("config
|
registered
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/authentication/NamespaceAuthenticationManagerTests.java
|
{
"start": 3845,
"end": 4170
}
|
class ____ {
@Autowired
void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.eraseCredentials(false)
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
}
}
@Configuration
@EnableWebSecurity
static
|
EraseCredentialsFalseConfig
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/checkpointing/RescaleCheckpointManuallyITCase.java
|
{
"start": 14700,
"end": 17348
}
|
class ____ extends RichParallelSourceFunction<Integer> {
private static final long serialVersionUID = 1L;
private final int numberKeys;
protected final int numberElements;
private final boolean failAfterEmission;
protected int counter = 0;
private boolean running = true;
public NotifyingDefiniteKeySource(
int numberKeys, int numberElements, boolean failAfterEmission) {
Preconditions.checkState(numberElements > 0);
this.numberKeys = numberKeys;
this.numberElements = numberElements;
this.failAfterEmission = failAfterEmission;
}
public boolean waitCheckpointCompleted() throws Exception {
return true;
}
@Override
public void run(SourceContext<Integer> ctx) throws Exception {
final int subtaskIndex = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask();
while (running) {
if (counter < numberElements) {
synchronized (ctx.getCheckpointLock()) {
for (int value = subtaskIndex;
value < numberKeys;
value +=
getRuntimeContext()
.getTaskInfo()
.getNumberOfParallelSubtasks()) {
ctx.collect(value);
}
counter++;
}
} else {
boolean newCheckpoint = false;
long waited = 0L;
running = false;
// maximum wait 5min
while (!newCheckpoint && waited < 300000L) {
synchronized (ctx.getCheckpointLock()) {
newCheckpoint = waitCheckpointCompleted();
}
if (!newCheckpoint) {
waited += 10L;
Thread.sleep(10L);
}
}
if (failAfterEmission) {
throw new FlinkRuntimeException(
"Make job fail artificially, to retain completed checkpoint.");
} else {
running = false;
}
}
}
}
@Override
public void cancel() {
running = false;
}
}
private static
|
NotifyingDefiniteKeySource
|
java
|
elastic__elasticsearch
|
x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/action/PutJobActionRequestTests.java
|
{
"start": 673,
"end": 1475
}
|
class ____ extends AbstractXContentSerializingTestCase<Request> {
private String jobId;
@Before
public void setupJobID() {
jobId = randomAlphaOfLengthBetween(1, 10);
}
@Override
protected Request createTestInstance() {
return new Request(ConfigTestHelpers.randomRollupJobConfig(random(), jobId));
}
@Override
protected Request mutateInstance(Request instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Writeable.Reader<Request> instanceReader() {
return Request::new;
}
@Override
protected Request doParseInstance(XContentParser parser) throws IOException {
return Request.fromXContent(parser, jobId);
}
}
|
PutJobActionRequestTests
|
java
|
apache__camel
|
components/camel-ignite/src/main/java/org/apache/camel/component/ignite/queue/IgniteQueueOperation.java
|
{
"start": 904,
"end": 1106
}
|
enum ____ {
CONTAINS,
ADD,
SIZE,
REMOVE,
ITERATOR,
CLEAR,
RETAIN_ALL,
ARRAY,
DRAIN,
ELEMENT,
PEEK,
OFFER,
POLL,
TAKE,
PUT
}
|
IgniteQueueOperation
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/lib/input/TestMRCJCFileInputFormat.java
|
{
"start": 1832,
"end": 6513
}
|
class ____ {
@Test
public void testAddInputPath() throws IOException {
final Configuration conf = new Configuration();
conf.set("fs.defaultFS", "file:///abc/");
final Job j = Job.getInstance(conf);
//setup default fs
final FileSystem defaultfs = FileSystem.get(conf);
System.out.println("defaultfs.getUri() = " + defaultfs.getUri());
{
//test addInputPath
final Path original = new Path("file:/foo");
System.out.println("original = " + original);
FileInputFormat.addInputPath(j, original);
final Path[] results = FileInputFormat.getInputPaths(j);
System.out.println("results = " + Arrays.asList(results));
assertEquals(1, results.length);
assertEquals(original, results[0]);
}
{
//test setInputPaths
final Path original = new Path("file:/bar");
System.out.println("original = " + original);
FileInputFormat.setInputPaths(j, original);
final Path[] results = FileInputFormat.getInputPaths(j);
System.out.println("results = " + Arrays.asList(results));
assertEquals(1, results.length);
assertEquals(original, results[0]);
}
}
@Test
public void testNumInputFiles() throws Exception {
Configuration conf = spy(new Configuration());
Job mockedJob = mock(Job.class);
when(mockedJob.getConfiguration()).thenReturn(conf);
FileStatus stat = mock(FileStatus.class);
when(stat.getLen()).thenReturn(0L);
TextInputFormat ispy = spy(new TextInputFormat());
doReturn(Arrays.asList(stat)).when(ispy).listStatus(mockedJob);
ispy.getSplits(mockedJob);
verify(conf).setLong(FileInputFormat.NUM_INPUT_FILES, 1);
}
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void testLastInputSplitAtSplitBoundary() throws Exception {
FileInputFormat fif = new FileInputFormatForTest(1024l * 1024 * 1024,
128l * 1024 * 1024);
Configuration conf = new Configuration();
JobContext jobContext = mock(JobContext.class);
when(jobContext.getConfiguration()).thenReturn(conf);
List<InputSplit> splits = fif.getSplits(jobContext);
assertEquals(8, splits.size());
for (int i = 0 ; i < splits.size() ; i++) {
InputSplit split = splits.get(i);
assertEquals(("host" + i), split.getLocations()[0]);
}
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testLastInputSplitExceedingSplitBoundary() throws Exception {
FileInputFormat fif = new FileInputFormatForTest(1027l * 1024 * 1024,
128l * 1024 * 1024);
Configuration conf = new Configuration();
JobContext jobContext = mock(JobContext.class);
when(jobContext.getConfiguration()).thenReturn(conf);
List<InputSplit> splits = fif.getSplits(jobContext);
assertEquals(8, splits.size());
for (int i = 0; i < splits.size(); i++) {
InputSplit split = splits.get(i);
assertEquals(("host" + i), split.getLocations()[0]);
}
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testLastInputSplitSingleSplit() throws Exception {
FileInputFormat fif = new FileInputFormatForTest(100l * 1024 * 1024,
128l * 1024 * 1024);
Configuration conf = new Configuration();
JobContext jobContext = mock(JobContext.class);
when(jobContext.getConfiguration()).thenReturn(conf);
List<InputSplit> splits = fif.getSplits(jobContext);
assertEquals(1, splits.size());
for (int i = 0; i < splits.size(); i++) {
InputSplit split = splits.get(i);
assertEquals(("host" + i), split.getLocations()[0]);
}
}
/**
* Test when the input file's length is 0.
*/
@Test
public void testForEmptyFile() throws Exception {
Configuration conf = new Configuration();
FileSystem fileSys = FileSystem.get(conf);
Path file = new Path("test" + "/file");
FSDataOutputStream out = fileSys.create(file, true,
conf.getInt("io.file.buffer.size", 4096), (short) 1, (long) 1024);
out.write(new byte[0]);
out.close();
// split it using a File input format
DummyInputFormat inFormat = new DummyInputFormat();
Job job = Job.getInstance(conf);
FileInputFormat.setInputPaths(job, "test");
List<InputSplit> splits = inFormat.getSplits(job);
assertEquals(1, splits.size());
FileSplit fileSplit = (FileSplit) splits.get(0);
assertEquals(0, fileSplit.getLocations().length);
assertEquals(file.getName(), fileSplit.getPath().getName());
assertEquals(0, fileSplit.getStart());
assertEquals(0, fileSplit.getLength());
fileSys.delete(file.getParent(), true);
}
/** Dummy
|
TestMRCJCFileInputFormat
|
java
|
quarkusio__quarkus
|
extensions/datasource/deployment-spi/src/main/java/io/quarkus/datasource/deployment/spi/DevServicesDatasourceResultBuildItem.java
|
{
"start": 285,
"end": 1356
}
|
class ____ extends SimpleBuildItem {
final Map<String, DbResult> dataSources;
public DevServicesDatasourceResultBuildItem(Map<String, DbResult> dataSources) {
this.dataSources = Collections.unmodifiableMap(dataSources);
}
public DbResult getDefaultDatasource() {
return dataSources.get(DataSourceUtil.DEFAULT_DATASOURCE_NAME);
}
public Map<String, DbResult> getNamedDatasources() {
return dataSources.entrySet().stream()
.filter(e -> !DataSourceUtil.isDefault(e.getKey()))
.collect(Collectors.toUnmodifiableMap(e -> e.getKey(), e -> e.getValue()));
}
public Map<String, DbResult> getDatasources() {
return dataSources;
}
public static DbResult resolve(Optional<DevServicesDatasourceResultBuildItem> devDbResultBuildItem, String dataSourceName) {
if (devDbResultBuildItem.isPresent()) {
return devDbResultBuildItem.get().dataSources.get(dataSourceName);
}
return null;
}
public static
|
DevServicesDatasourceResultBuildItem
|
java
|
hibernate__hibernate-orm
|
local-build-plugins/src/main/java/org/hibernate/orm/properties/jdk11/DomToAsciidocConverter.java
|
{
"start": 387,
"end": 4984
}
|
class ____ {
public static String convert(Elements elements) {
final DomToAsciidocConverter converter = new DomToAsciidocConverter();
return converter.convertInternal( elements );
}
public static String convert(Element element) {
final DomToAsciidocConverter converter = new DomToAsciidocConverter();
return converter.convertInternal( element );
}
private final Map<String, Consumer<Element>> elementVisitorsByTag = new HashMap<>();
private final StringBuilder converted = new StringBuilder();
public DomToAsciidocConverter() {
elementVisitorsByTag.put( "a", this::visitLink );
elementVisitorsByTag.put( "span", this::visitSpan );
elementVisitorsByTag.put( "ul", this::visitUl );
elementVisitorsByTag.put( "ol", this::visitUl );
elementVisitorsByTag.put( "li", this::visitLi );
elementVisitorsByTag.put( "b", this::visitBold );
elementVisitorsByTag.put( "strong", this::visitBold );
elementVisitorsByTag.put( "em", this::visitBold );
elementVisitorsByTag.put( "code", this::visitCode );
elementVisitorsByTag.put( "p", this::visitDiv );
elementVisitorsByTag.put( "div", this::visitDiv );
elementVisitorsByTag.put( "dl", this::visitDiv );
elementVisitorsByTag.put( "dd", this::visitDiv );
}
private String convertInternal(Elements elements) {
for ( Element element : elements ) {
visitElement( element );
}
return converted.toString();
}
private String convertInternal(Element element) {
visitElement( element );
return converted.toString();
}
private void visitNode(Node node) {
// We know about 2 types of nodes that we care about:
// 1. Element -- means that it is some tag,
// so we will defer the decision what to do about it to the visitElement.
// 2. TextNode -- simple text that we'll just add to the converted result.
//
// If we encounter something else -- let's fail,
// so we can investigate what new element type it is and decide what to do about it.
if ( node instanceof Element ) {
visitElement( ( (Element) node ) );
}
else if ( node instanceof TextNode ) {
visitTextNode( (TextNode) node );
}
else {
visitUnknownNode( node );
}
}
private void visitElement(Element element) {
String tag = element.tagName();
Consumer<Element> visitor = elementVisitorsByTag.get( tag );
if ( visitor == null ) {
// If we encounter an element that we are not handling --
// we want to fail as the result might be missing some details:
throw new IllegalStateException( "Unknown element: " + element );
}
visitor.accept( element );
}
private void visitDiv(Element div) {
for ( Node childNode : div.childNodes() ) {
visitNode( childNode );
}
converted.append( '\n' );
}
private void visitCode(Element code) {
converted.append( "`" );
for ( Node childNode : code.childNodes() ) {
visitNode( childNode );
}
converted.append( "`" );
}
private void visitBold(Element bold) {
converted.append( "**" );
for ( Node childNode : bold.childNodes() ) {
visitNode( childNode );
}
converted.append( "**" );
}
private void visitLi(Element li) {
converted.append( "\n * " );
for ( Node childNode : li.childNodes() ) {
visitNode( childNode );
}
}
private void visitUl(Element ul) {
if ( converted.lastIndexOf( "\n" ) != converted.length() - 1 ) {
converted.append( '\n' );
}
for ( Node childNode : ul.childNodes() ) {
visitNode( childNode );
}
}
private void visitSpan(Element span) {
// If it is a label for deprecation, let's make it bold to stand out:
boolean deprecatedLabel = span.hasClass( "deprecatedLabel" );
if ( deprecatedLabel ) {
converted.append( "**" );
}
for ( Node childNode : span.childNodes() ) {
visitNode( childNode );
}
if ( deprecatedLabel ) {
converted.append( "**" );
}
}
private void visitLink(Element link) {
converted.append( "link:" )
.append( link.attr( "href" ) )
.append( '[' );
for ( Node childNode : link.childNodes() ) {
visitNode( childNode );
}
converted.append( ']' );
}
private void visitTextNode(TextNode node) {
if ( converted.lastIndexOf( "+\n" ) == converted.length() - "+\n".length() ) {
// if it's a start of a paragraph - remove any leading spaces:
converted.append( ( node ).text().replaceAll( "^\\s+", "" ) );
}
else {
converted.append( ( node ).text() );
}
}
private void visitUnknownNode(Node node) {
// if we encounter a node that we are not handling - we want to fail as the result might be missing some details:
throw new IllegalStateException( "Unknown node: " + node );
}
}
|
DomToAsciidocConverter
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/ByteBufferReadable.java
|
{
"start": 1184,
"end": 2490
}
|
interface ____ {
/**
* Reads up to buf.remaining() bytes into buf. Callers should use
* buf.limit(..) to control the size of the desired read.
* <p>
* After a successful call, {@code buf.position()} will be advanced by the
* number of bytes read and {@code buf.limit()} will be unchanged.
* <p>
* In the case of an exception, the state of the buffer (the contents of the
* buffer, the {@code buf.position()}, the {@code buf.limit()}, etc.) is
* undefined, and callers should be prepared to recover from this
* eventuality.
* <p>
* Callers should use {@link StreamCapabilities#hasCapability(String)} with
* {@link StreamCapabilities#READBYTEBUFFER} to check if the underlying
* stream supports this interface, otherwise they might get a
* {@link UnsupportedOperationException}.
* <p>
* Implementations should treat 0-length requests as legitimate, and must not
* signal an error upon their receipt.
*
* @param buf
* the ByteBuffer to receive the results of the read operation.
* @return the number of bytes read, possibly zero, or -1 if
* reach end-of-stream
* @throws IOException
* if there is some error performing the read
*/
public int read(ByteBuffer buf) throws IOException;
}
|
ByteBufferReadable
|
java
|
apache__avro
|
lang/java/trevni/avro/src/test/java/org/apache/trevni/avro/mapreduce/TestKeyValueWordCount.java
|
{
"start": 2079,
"end": 2836
}
|
class ____ extends Mapper<AvroKey<String>, NullWritable, Text, LongWritable> {
private LongWritable mCount = new LongWritable();
private Text mText = new Text();
@Override
protected void setup(Context context) {
mCount.set(1);
}
@Override
protected void map(AvroKey<String> key, NullWritable value, Context context)
throws IOException, InterruptedException {
try {
StringTokenizer tokens = new StringTokenizer(key.datum());
while (tokens.hasMoreTokens()) {
mText.set(tokens.nextToken());
context.write(mText, mCount);
}
} catch (Exception e) {
throw new RuntimeException(key + " " + key.datum(), e);
}
}
}
private static
|
WordCountMapper
|
java
|
google__guava
|
guava/src/com/google/common/collect/CompactHashMap.java
|
{
"start": 34413,
"end": 40560
}
|
class ____ extends Maps.Values<K, V> {
ValuesView() {
super(CompactHashMap.this);
}
@Override
public Iterator<V> iterator() {
return valuesIterator();
}
@Override
public void forEach(Consumer<? super V> action) {
checkNotNull(action);
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
delegate.values().forEach(action);
} else {
for (int i = firstEntryIndex(); i >= 0; i = getSuccessor(i)) {
action.accept(value(i));
}
}
}
@Override
public Spliterator<V> spliterator() {
if (needsAllocArrays()) {
return Spliterators.spliterator(new Object[0], Spliterator.ORDERED);
}
Map<K, V> delegate = delegateOrNull();
return (delegate != null)
? delegate.values().spliterator()
: Spliterators.spliterator(requireValues(), 0, size, Spliterator.ORDERED);
}
@Override
public @Nullable Object[] toArray() {
if (needsAllocArrays()) {
return new Object[0];
}
Map<K, V> delegate = delegateOrNull();
return (delegate != null)
? delegate.values().toArray()
: ObjectArrays.copyAsObjectArray(requireValues(), 0, size);
}
@Override
@SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
public <T extends @Nullable Object> T[] toArray(T[] a) {
if (needsAllocArrays()) {
if (a.length > 0) {
@Nullable Object[] unsoundlyCovariantArray = a;
unsoundlyCovariantArray[0] = null;
}
return a;
}
Map<K, V> delegate = delegateOrNull();
return (delegate != null)
? delegate.values().toArray(a)
: ObjectArrays.toArrayImpl(requireValues(), 0, size, a);
}
}
Iterator<V> valuesIterator() {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.values().iterator();
}
return new Itr<V>() {
@Override
@ParametricNullness
V getOutput(int entry) {
return value(entry);
}
};
}
/**
* Ensures that this {@code CompactHashMap} has the smallest representation in memory, given its
* current size.
*/
public void trimToSize() {
if (needsAllocArrays()) {
return;
}
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
Map<K, V> newDelegate = createHashFloodingResistantDelegate(size());
newDelegate.putAll(delegate);
this.table = newDelegate;
return;
}
int size = this.size;
if (size < requireEntries().length) {
resizeEntries(size);
}
int minimumTableSize = CompactHashing.tableSize(size);
int mask = hashTableMask();
if (minimumTableSize < mask) { // smaller table size will always be less than current mask
resizeTable(mask, minimumTableSize, UNSET, UNSET);
}
}
@Override
public void clear() {
if (needsAllocArrays()) {
return;
}
incrementModCount();
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
metadata =
Ints.constrainToRange(size(), CompactHashing.DEFAULT_SIZE, CompactHashing.MAX_SIZE);
delegate.clear(); // invalidate any iterators left over!
table = null;
size = 0;
} else {
Arrays.fill(requireKeys(), 0, size, null);
Arrays.fill(requireValues(), 0, size, null);
CompactHashing.tableClear(requireTable());
Arrays.fill(requireEntries(), 0, size, 0);
this.size = 0;
}
}
@J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
Iterator<Entry<K, V>> entryIterator = entrySetIterator();
while (entryIterator.hasNext()) {
Entry<K, V> e = entryIterator.next();
stream.writeObject(e.getKey());
stream.writeObject(e.getValue());
}
}
@SuppressWarnings("unchecked")
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int elementCount = stream.readInt();
if (elementCount < 0) {
throw new InvalidObjectException("Invalid size: " + elementCount);
}
init(elementCount);
for (int i = 0; i < elementCount; i++) {
K key = (K) stream.readObject();
V value = (V) stream.readObject();
put(key, value);
}
}
/*
* The following methods are safe to call as long as both of the following hold:
*
* - allocArrays() has been called. Callers can confirm this by checking needsAllocArrays().
*
* - The map has not switched to delegating to a java.util implementation to mitigate hash
* flooding. Callers can confirm this by null-checking delegateOrNull().
*
* In an ideal world, we would document why we know those things are true every time we call these
* methods. But that is a bit too painful....
*/
private Object requireTable() {
return requireNonNull(table);
}
private int[] requireEntries() {
return requireNonNull(entries);
}
private @Nullable Object[] requireKeys() {
return requireNonNull(keys);
}
private @Nullable Object[] requireValues() {
return requireNonNull(values);
}
/*
* The following methods are safe to call as long as the conditions in the *previous* comment are
* met *and* the index is less than size().
*
* (The above explains when these methods are safe from a `nullness` perspective. From an
* `unchecked` perspective, they're safe because we put only K/V elements into each array.)
*/
@SuppressWarnings("unchecked")
private K key(int i) {
return (K) requireKeys()[i];
}
@SuppressWarnings("unchecked")
private V value(int i) {
return (V) requireValues()[i];
}
private int entry(int i) {
return requireEntries()[i];
}
private void setKey(int i, K key) {
requireKeys()[i] = key;
}
private void setValue(int i, V value) {
requireValues()[i] = value;
}
private void setEntry(int i, int value) {
requireEntries()[i] = value;
}
}
|
ValuesView
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/kstream/ValueTransformerWithKeySupplier.java
|
{
"start": 1665,
"end": 2389
}
|
interface ____<K, V, VR> extends ConnectedStoreProvider, Supplier<ValueTransformerWithKey<K, V, VR>> {
/**
* Return a newly constructed {@link ValueTransformerWithKey} instance.
* The supplier should always generate a new instance each time {@link ValueTransformerWithKeySupplier#get()} gets called.
* <p>
* Creating a single {@link ValueTransformerWithKey} object and returning the same object reference in {@link ValueTransformerWithKeySupplier#get()}
* is a violation of the supplier pattern and leads to runtime exceptions.
*
* @return a newly constructed {@link ValueTransformerWithKey} instance
*/
ValueTransformerWithKey<K, V, VR> get();
}
|
ValueTransformerWithKeySupplier
|
java
|
google__guava
|
guava/src/com/google/common/util/concurrent/AbstractFutureState.java
|
{
"start": 33782,
"end": 35637
}
|
class ____ extends AtomicHelper {
@Override
void putThread(Waiter waiter, Thread newValue) {
waiter.thread = newValue;
}
@Override
void putNext(Waiter waiter, @Nullable Waiter newValue) {
waiter.next = newValue;
}
@Override
boolean casWaiters(
AbstractFutureState<?> future, @Nullable Waiter expect, @Nullable Waiter update) {
synchronized (future) {
if (future.waitersField == expect) {
future.waitersField = update;
return true;
}
return false;
}
}
@Override
boolean casListeners(
AbstractFutureState<?> future, @Nullable Listener expect, Listener update) {
synchronized (future) {
if (future.listenersField == expect) {
future.listenersField = update;
return true;
}
return false;
}
}
@Override
@Nullable Listener gasListeners(AbstractFutureState<?> future, Listener update) {
synchronized (future) {
Listener old = future.listenersField;
if (old != update) {
future.listenersField = update;
}
return old;
}
}
@Override
@Nullable Waiter gasWaiters(AbstractFutureState<?> future, Waiter update) {
synchronized (future) {
Waiter old = future.waitersField;
if (old != update) {
future.waitersField = update;
}
return old;
}
}
@Override
boolean casValue(AbstractFutureState<?> future, @Nullable Object expect, Object update) {
synchronized (future) {
if (future.valueField == expect) {
future.valueField = update;
return true;
}
return false;
}
}
@Override
String atomicHelperTypeForTest() {
return "SynchronizedHelper";
}
}
}
|
SynchronizedHelper
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/query/spi/SqlOmittingQueryOptions.java
|
{
"start": 544,
"end": 3600
}
|
class ____ extends DelegatingQueryOptions {
private final boolean omitLimit;
private final boolean omitLocks;
private final ListResultsConsumer.UniqueSemantic uniqueSemantic;
public SqlOmittingQueryOptions(QueryOptions queryOptions, boolean omitLimit, boolean omitLocks) {
super( queryOptions );
this.omitLimit = omitLimit;
this.omitLocks = omitLocks;
uniqueSemantic = null;
}
public SqlOmittingQueryOptions(QueryOptions queryOptions, boolean omitLimit, boolean omitLocks, ListResultsConsumer.UniqueSemantic semantic) {
super( queryOptions );
this.omitLimit = omitLimit;
this.omitLocks = omitLocks;
this.uniqueSemantic = semantic;
}
public static QueryOptions omitSqlQueryOptions(QueryOptions originalOptions) {
return omitSqlQueryOptions( originalOptions, true, true );
}
public static QueryOptions omitSqlQueryOptions(QueryOptions originalOptions, JdbcSelect select) {
return omitSqlQueryOptions( originalOptions, !select.usesLimitParameters(), false );
}
public static QueryOptions omitSqlQueryOptions(QueryOptions originalOptions, boolean omitLimit, boolean omitLocks) {
final Limit limit = originalOptions.getLimit();
// No need for a context when there are no options we use during SQL rendering
if ( originalOptions.getLockOptions().isEmpty() ) {
if ( !omitLimit || limit == null || limit.isEmpty() ) {
return originalOptions;
}
}
if ( !omitLocks ) {
if ( !omitLimit || limit == null || limit.isEmpty() ) {
return originalOptions;
}
}
return new SqlOmittingQueryOptions( originalOptions, omitLimit, omitLocks );
}
public static QueryOptions omitSqlQueryOptionsWithUniqueSemanticFilter(QueryOptions originalOptions, boolean omitLimit, boolean omitLocks) {
final Limit limit = originalOptions.getLimit();
// No need for a context when there are no options we use during SQL rendering
if ( originalOptions.getLockOptions().isEmpty() ) {
if ( !omitLimit || limit == null || limit.isEmpty() ) {
return originalOptions;
}
}
if ( !omitLocks ) {
if ( !omitLimit || limit == null || limit.isEmpty() ) {
return originalOptions;
}
}
return new SqlOmittingQueryOptions( originalOptions, omitLimit, omitLocks, ListResultsConsumer.UniqueSemantic.FILTER );
}
@Override
public LockOptions getLockOptions() {
return omitLocks ? new LockOptions() : super.getLockOptions();
}
@Override
public Integer getFetchSize() {
return null;
}
@Override
public Limit getLimit() {
return omitLimit ? Limit.NONE : super.getLimit();
}
@Override
public Integer getFirstRow() {
return omitLimit ? null : super.getFirstRow();
}
@Override
public Integer getMaxRows() {
return omitLimit ? null : super.getMaxRows();
}
@Override
public Limit getEffectiveLimit() {
return omitLimit ? Limit.NONE : super.getEffectiveLimit();
}
@Override
public boolean hasLimit() {
return !omitLimit && super.hasLimit();
}
@Override
public ListResultsConsumer.UniqueSemantic getUniqueSemantic() {
return uniqueSemantic;
}
}
|
SqlOmittingQueryOptions
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/cluster/metadata/MetadataMappingService.java
|
{
"start": 3869,
"end": 14793
}
|
class ____ implements ClusterStateTaskExecutor<PutMappingClusterStateUpdateTask> {
private final IndexSettingProviders indexSettingProviders;
PutMappingExecutor() {
this(IndexSettingProviders.EMPTY);
}
PutMappingExecutor(IndexSettingProviders indexSettingProviders) {
this.indexSettingProviders = indexSettingProviders;
}
@Override
public ClusterState execute(BatchExecutionContext<PutMappingClusterStateUpdateTask> batchExecutionContext) throws Exception {
Map<Index, MapperService> indexMapperServices = new HashMap<>();
try {
var currentState = batchExecutionContext.initialState();
for (final var taskContext : batchExecutionContext.taskContexts()) {
final var task = taskContext.getTask();
final PutMappingClusterStateUpdateRequest request = task.request;
try (var ignored = taskContext.captureResponseHeaders()) {
for (Index index : request.indices()) {
final IndexMetadata indexMetadata = currentState.metadata().indexMetadata(index);
if (indexMapperServices.containsKey(indexMetadata.getIndex()) == false) {
MapperService mapperService = indicesService.createIndexMapperServiceForValidation(indexMetadata);
indexMapperServices.put(index, mapperService);
// add mappings for all types, we need them for cross-type validation
mapperService.merge(indexMetadata, MergeReason.MAPPING_RECOVERY);
}
}
currentState = applyRequest(currentState, request, indexMapperServices);
taskContext.success(task);
} catch (Exception e) {
taskContext.onFailure(e);
}
}
return currentState;
} finally {
IOUtils.close(indexMapperServices.values());
}
}
private ClusterState applyRequest(
ClusterState currentState,
PutMappingClusterStateUpdateRequest request,
Map<Index, MapperService> indexMapperServices
) {
final CompressedXContent mappingUpdateSource = request.source();
final Metadata metadata = currentState.metadata();
final List<IndexMetadata> updateList = new ArrayList<>();
MergeReason reason = request.autoUpdate() ? MergeReason.MAPPING_AUTO_UPDATE : MergeReason.MAPPING_UPDATE;
for (Index index : request.indices()) {
MapperService mapperService = indexMapperServices.get(index);
// IMPORTANT: always get the metadata from the state since it get's batched
// and if we pull it from the indexService we might miss an update etc.
final IndexMetadata indexMetadata = metadata.indexMetadata(index);
DocumentMapper existingMapper = mapperService.documentMapper();
if (existingMapper != null && existingMapper.mappingSource().equals(mappingUpdateSource)) {
continue;
}
// this is paranoia... just to be sure we use the exact same metadata tuple on the update that
// we used for the validation, it makes this mechanism little less scary (a little)
updateList.add(indexMetadata);
// try and parse it (no need to add it here) so we can bail early in case of parsing exception
// first, simulate: just call merge and ignore the result
Mapping mapping = mapperService.parseMapping(MapperService.SINGLE_MAPPING_NAME, reason, mappingUpdateSource);
MapperService.mergeMappings(mapperService.documentMapper(), mapping, reason, mapperService.getIndexSettings());
}
Metadata.Builder builder = Metadata.builder(metadata);
boolean updated = false;
for (IndexMetadata indexMetadata : updateList) {
boolean updatedMapping = false;
// do the actual merge here on the master, and update the mapping source
// we use the exact same indexService and metadata we used to validate above here to actually apply the update
final Index index = indexMetadata.getIndex();
final MapperService mapperService = indexMapperServices.get(index);
CompressedXContent existingSource = null;
DocumentMapper existingMapper = mapperService.documentMapper();
if (existingMapper != null) {
existingSource = existingMapper.mappingSource();
}
DocumentMapper mergedMapper = mapperService.merge(MapperService.SINGLE_MAPPING_NAME, mappingUpdateSource, reason);
CompressedXContent updatedSource = mergedMapper.mappingSource();
if (existingSource != null) {
if (existingSource.equals(updatedSource)) {
// same source, no changes, ignore it
} else {
updatedMapping = true;
// use the merged mapping source
if (logger.isDebugEnabled()) {
logger.debug("{} update_mapping [{}] with source [{}]", index, mergedMapper.type(), updatedSource);
} else if (logger.isInfoEnabled()) {
logger.info("{} update_mapping [{}]", index, mergedMapper.type());
}
}
} else {
updatedMapping = true;
if (logger.isDebugEnabled()) {
logger.debug("{} create_mapping with source [{}]", index, updatedSource);
} else if (logger.isInfoEnabled()) {
logger.info("{} create_mapping", index);
}
}
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(indexMetadata);
// Mapping updates on a single type may have side-effects on other types so we need to
// update mapping metadata on all types
DocumentMapper docMapper = mapperService.documentMapper();
if (docMapper != null) {
indexMetadataBuilder.putMapping(new MappingMetadata(docMapper));
indexMetadataBuilder.putInferenceFields(docMapper.mappers().inferenceFields());
}
boolean updatedSettings = false;
final Settings.Builder additionalIndexSettings = Settings.builder();
if (updatedMapping) {
indexMetadataBuilder.mappingVersion(1 + indexMetadataBuilder.mappingVersion())
.mappingsUpdatedVersion(IndexVersion.current());
for (IndexSettingProvider provider : indexSettingProviders.getIndexSettingProviders()) {
Settings.Builder newAdditionalSettingsBuilder = Settings.builder();
provider.onUpdateMappings(indexMetadata, docMapper, newAdditionalSettingsBuilder);
if (newAdditionalSettingsBuilder.keys().isEmpty() == false) {
Settings newAdditionalSettings = newAdditionalSettingsBuilder.build();
MetadataCreateIndexService.validateAdditionalSettings(provider, newAdditionalSettings, additionalIndexSettings);
additionalIndexSettings.put(newAdditionalSettings);
updatedSettings = true;
}
}
}
if (updatedSettings) {
final Settings.Builder indexSettingsBuilder = Settings.builder();
indexSettingsBuilder.put(indexMetadata.getSettings());
indexSettingsBuilder.put(additionalIndexSettings.build());
indexMetadataBuilder.settings(indexSettingsBuilder.build());
indexMetadataBuilder.settingsVersion(1 + indexMetadata.getSettingsVersion());
}
/*
* This implicitly increments the index metadata version and builds the index metadata. This means that we need to have
* already incremented the mapping version if necessary. Therefore, the mapping version increment must remain before this
* statement.
*/
builder.getProject(metadata.projectFor(index).id()).put(indexMetadataBuilder);
updated |= updatedMapping;
}
if (updated) {
return ClusterState.builder(currentState).metadata(builder).build();
} else {
return currentState;
}
}
}
public void putMapping(final PutMappingClusterStateUpdateRequest request, final ActionListener<AcknowledgedResponse> listener) {
final ClusterState state = clusterService.state();
boolean noop = true;
for (Index index : request.indices()) {
var project = state.metadata().lookupProject(index);
if (project.isEmpty()) {
// this is a race condition where the project got deleted from under a mapping update task
noop = false;
break;
}
final IndexMetadata indexMetadata = project.get().index(index);
if (indexMetadata == null) {
// local store recovery sends a mapping update request during application of a cluster state on the data node which we might
// receive here before the CS update that created the index has been applied on all nodes and thus the index isn't found in
// the state yet, but will be visible to the CS update below
noop = false;
break;
}
final MappingMetadata mappingMetadata = indexMetadata.mapping();
if (mappingMetadata == null) {
noop = false;
break;
}
if (request.source().equals(mappingMetadata.source()) == false) {
noop = false;
break;
}
}
if (noop) {
listener.onResponse(AcknowledgedResponse.TRUE);
return;
}
taskQueue.submitTask(
"put-mapping " + Strings.arrayToCommaDelimitedString(request.indices()),
new PutMappingClusterStateUpdateTask(request, listener),
request.masterNodeTimeout()
);
}
}
|
PutMappingExecutor
|
java
|
elastic__elasticsearch
|
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/CompressedExponentialHistogram.java
|
{
"start": 7445,
"end": 8535
}
|
class ____ implements CopyableBucketIterator {
private final CompressedHistogramData.BucketsDecoder decoder;
CompressedBucketsIterator(CompressedHistogramData.BucketsDecoder delegate) {
this.decoder = delegate;
}
@Override
public CopyableBucketIterator copy() {
return new CompressedBucketsIterator(decoder.copy());
}
@Override
public final boolean hasNext() {
return decoder.hasNext();
}
@Override
public final long peekCount() {
return decoder.peekCount();
}
@Override
public final long peekIndex() {
return decoder.peekIndex();
}
@Override
public int scale() {
return CompressedExponentialHistogram.this.scale();
}
@Override
public final void advance() {
decoder.advance();
}
}
}
}
|
CompressedBucketsIterator
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/config/SslVerificationMode.java
|
{
"start": 688,
"end": 981
}
|
enum ____ {
/**
* No SSL certificate verification.
*/
NONE,
/**
* Validate the certificate chain but ignore hostname verification.
*/
CA_ONLY,
/**
* Complete validation of the certificate chain and hostname.
*/
STRICT
}
|
SslVerificationMode
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/submitted/annotion_many_one_add_columnprefix/User.java
|
{
"start": 754,
"end": 1810
}
|
class ____ {
private Integer id;
private String username;
private List<User> teachers;
private Role role;
private List<Role> roles;
private User friend;
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", username='" + username + '\'' + ", roles=" + roles + '}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public List<User> getTeachers() {
return teachers;
}
public void setTeachers(List<User> teachers) {
this.teachers = teachers;
}
public User getFriend() {
return friend;
}
public void setFriend(User friend) {
this.friend = friend;
}
}
|
User
|
java
|
grpc__grpc-java
|
core/src/main/java/io/grpc/internal/MessageDeframer.java
|
{
"start": 1416,
"end": 1797
}
|
class ____ implements Closeable, Deframer {
private static final int HEADER_LENGTH = 5;
private static final int COMPRESSED_FLAG_MASK = 1;
private static final int RESERVED_MASK = 0xFE;
private static final int MAX_BUFFER_SIZE = 1024 * 1024 * 2;
/**
* A listener of deframing events. These methods will be invoked from the deframing thread.
*/
public
|
MessageDeframer
|
java
|
apache__camel
|
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/annotation/WithMainClassTest.java
|
{
"start": 1364,
"end": 1465
}
|
class ____ the application to test can be specified.
*/
@CamelMainTest(mainClass = MyMainClass.class)
|
of
|
java
|
quarkusio__quarkus
|
extensions/jdbc/jdbc-oracle/deployment/src/test/java/io/quarkus/jdbc/oracle/deployment/DevServicesOracleDatasourceTestCase.java
|
{
"start": 715,
"end": 2433
}
|
class ____ {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.withEmptyApplication()
// Expect no warnings (in particular from Agroal)
.setLogRecordPredicate(record -> record.getLevel().intValue() >= Level.WARNING.intValue()
// There are other warnings: JDK8, TestContainers, drivers, ...
// Ignore them: we're only interested in Agroal here.
&& record.getMessage().contains("Agroal"))
.assertLogRecords(records -> assertThat(records)
// This is just to get meaningful error messages, as LogRecord doesn't have a toString()
.extracting(LogRecord::getMessage)
.isEmpty());
@Inject
AgroalDataSource dataSource;
@Test
public void testDatasource() throws Exception {
AgroalConnectionPoolConfiguration configuration = null;
try {
configuration = dataSource.getConfiguration().connectionPoolConfiguration();
} catch (NullPointerException e) {
// we catch the NPE here as we have a proxycd and we can't test dataSource directly
fail("Datasource should not be null");
}
assertTrue(configuration.connectionFactoryConfiguration().jdbcUrl().contains("jdbc:oracle:"));
assertEquals("quarkus", configuration.connectionFactoryConfiguration().principal().getName());
assertEquals(50, configuration.maxSize());
assertThat(configuration.exceptionSorter()).isInstanceOf(OracleExceptionSorter.class);
try (Connection connection = dataSource.getConnection()) {
}
}
}
|
DevServicesOracleDatasourceTestCase
|
java
|
spring-projects__spring-framework
|
spring-jdbc/src/main/java/org/springframework/jdbc/core/SqlProvider.java
|
{
"start": 1186,
"end": 1413
}
|
interface ____ {
/**
* Return the SQL string for this object, i.e.
* typically the SQL used for creating statements.
* @return the SQL string, or {@code null} if not available
*/
@Nullable String getSql();
}
|
SqlProvider
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/action/support/single/shard/TransportSingleShardAction.java
|
{
"start": 12447,
"end": 12951
}
|
class ____ {
final Request request;
final String concreteIndex;
InternalRequest(Request request, String concreteIndex) {
this.request = request;
this.concreteIndex = concreteIndex;
}
public Request request() {
return request;
}
public String concreteIndex() {
return concreteIndex;
}
}
protected Executor getExecutor(ShardId shardId) {
return executor;
}
}
|
InternalRequest
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/VariantSerializerUpgradeTest.java
|
{
"start": 4223,
"end": 5737
}
|
class ____ implements UpgradeVerifier<Variant> {
@Override
public TypeSerializer<Variant> createUpgradedSerializer() {
return VariantSerializer.INSTANCE;
}
@Override
public Condition<Variant> testDataCondition() {
VariantBuilder builder = Variant.newBuilder();
Variant data =
builder.object()
.add("k", builder.of(1))
.add("object", builder.object().add("k", builder.of("hello")).build())
.add(
"array",
builder.array()
.add(builder.of(1))
.add(builder.of(2))
.add(
builder.object()
.add("kk", builder.of(1.123f))
.build())
.build())
.build();
return new Condition<>(data::equals, "value is " + data);
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Variant>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
}
|
VariantSerializerVerifier
|
java
|
assertj__assertj-core
|
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/fields/RecursiveComparisonAssert_isEqualTo_with_optional_Test.java
|
{
"start": 6197,
"end": 7007
}
|
class ____ {
Optional<Author> coAuthor;
OptionalInt numberOfPages;
OptionalLong bookId;
OptionalDouble price;
public BookWithOptionalCoAuthor(String coAuthor) {
this.coAuthor = Optional.ofNullable(coAuthor == null ? null : new Author(coAuthor));
}
public BookWithOptionalCoAuthor() {
this.coAuthor = null;
}
public BookWithOptionalCoAuthor(String coAuthor, int numberOfPages, long bookId, double price) {
this.coAuthor = Optional.ofNullable(coAuthor == null ? null : new Author(coAuthor));
this.numberOfPages = OptionalInt.of(numberOfPages);
this.bookId = OptionalLong.of(bookId);
this.price = OptionalDouble.of(price);
}
public Optional<Author> getCoAuthor() {
return coAuthor;
}
}
static
|
BookWithOptionalCoAuthor
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/ingest/LogstashInternalBridgeTests.java
|
{
"start": 969,
"end": 2363
}
|
class ____ extends ESTestCase {
public void testIngestDocumentRerouteBridge() {
final IngestDocument ingestDocument = emptyIngestDocument();
ingestDocument.setFieldValue("_index", "nowhere");
assertThat(ingestDocument.getFieldValue("_index", String.class), is(equalTo("nowhere")));
assertThat(LogstashInternalBridge.isReroute(ingestDocument), is(false));
ingestDocument.reroute("somewhere");
assertThat(ingestDocument.getFieldValue("_index", String.class), is(equalTo("somewhere")));
assertThat(LogstashInternalBridge.isReroute(ingestDocument), is(true));
LogstashInternalBridge.resetReroute(ingestDocument);
assertThat(ingestDocument.getFieldValue("_index", String.class), is(equalTo("somewhere")));
assertThat(LogstashInternalBridge.isReroute(ingestDocument), is(false));
}
public void testCreateThreadPool() {
final Settings settings = Settings.builder().put(Node.NODE_NAME_SETTING.getKey(), "TEST").build();
ThreadPool threadPool = null;
try {
threadPool = LogstashInternalBridge.createThreadPool(settings);
assertThat(threadPool, is(notNullValue()));
} finally {
if (Objects.nonNull(threadPool)) {
ThreadPool.terminate(threadPool, 10L, TimeUnit.SECONDS);
}
}
}
}
|
LogstashInternalBridgeTests
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/JobConf.java
|
{
"start": 63539,
"end": 63693
}
|
class ____ be invoked in order to send a notification
* after the job has completed (success/failure).
*
* @return the fully-qualified name of the
|
to
|
java
|
spring-projects__spring-boot
|
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/scan/ScanFactoryBean.java
|
{
"start": 785,
"end": 1174
}
|
class ____ implements FactoryBean<ScanBean> {
ScanFactoryBean(String value) {
Assert.state(!value.contains("$"), "value should not contain '$'");
}
@Override
public ScanBean getObject() {
return new ScanBean("fromFactory");
}
@Override
public Class<?> getObjectType() {
return ScanBean.class;
}
@Override
public boolean isSingleton() {
return false;
}
}
|
ScanFactoryBean
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/DesiredBalanceComputerTests.java
|
{
"start": 65675,
"end": 100532
}
|
class ____ {
private final Map<String, DiskUsage> diskUsage = new HashMap<>();
private final Map<String, Long> shardSizes = new HashMap<>();
private final Map<NodeAndPath, ReservedSpace> reservedSpace = new HashMap<>();
private final Map<NodeAndShard, String> dataPath = new HashMap<>();
public ClusterInfoTestBuilder withNode(String nodeId, long totalBytes, long freeBytes) {
diskUsage.put(nodeId, new DiskUsage(nodeId, nodeId, "/path", totalBytes, freeBytes));
return this;
}
public ClusterInfoTestBuilder withNodeUsedSpace(String nodeId, long usedBytes) {
diskUsage.compute(nodeId, (key, usage) -> {
assertThat(usage, notNullValue());
return new DiskUsage(usage.nodeId(), usage.nodeName(), usage.path(), usage.totalBytes(), usage.freeBytes() - usedBytes);
});
return this;
}
public ClusterInfoTestBuilder withShard(ShardId shardId, boolean primary, long size) {
shardSizes.put(shardIdentifierFromRouting(shardId, primary), size);
return this;
}
public ClusterInfoTestBuilder withShard(ShardRouting shard, long size) {
shardSizes.put(shardIdentifierFromRouting(shard), size);
if (shard.unassigned() == false) {
dataPath.put(NodeAndShard.from(shard), "/data/path");
}
return this;
}
public ClusterInfoTestBuilder withReservedSpace(String nodeId, long size, ShardId... shardIds) {
reservedSpace.put(new NodeAndPath(nodeId, "/path"), new ReservedSpace(size, Set.of(shardIds)));
return this;
}
public ClusterInfo build() {
return ClusterInfo.builder()
.leastAvailableSpaceUsage(diskUsage)
.mostAvailableSpaceUsage(diskUsage)
.shardSizes(shardSizes)
.reservedSpace(reservedSpace)
.dataPath(dataPath)
.build();
}
}
private static IndexId indexIdFrom(IndexMetadata indexMetadata) {
return new IndexId(indexMetadata.getIndex().getName(), indexMetadata.getIndex().getUUID());
}
private static ShardId shardIdFrom(IndexMetadata indexMetadata, int shardId) {
return new ShardId(indexMetadata.getIndex(), shardId);
}
public void testShouldLogComputationIteration() {
checkIterationLogging(
999,
10L,
new MockLog.UnseenEventExpectation(
"Should not report long computation too early",
DesiredBalanceComputer.class.getCanonicalName(),
Level.INFO,
"Desired balance computation for [*] is still not converged after [*] and [*] iterations"
)
);
checkIterationLogging(
1001,
10L,
new MockLog.SeenEventExpectation(
"Should report long computation based on iteration count",
DesiredBalanceComputer.class.getCanonicalName(),
Level.INFO,
"Desired balance computation for [*] is still not converged after [10s] and [1000] iterations"
)
);
checkIterationLogging(
61,
1000L,
new MockLog.SeenEventExpectation(
"Should report long computation based on time",
DesiredBalanceComputer.class.getCanonicalName(),
Level.INFO,
"Desired balance computation for [*] is still not converged after [1m] and [59] iterations"
)
);
}
private void checkIterationLogging(int iterations, long eachIterationDuration, MockLog.AbstractEventExpectation expectation) {
var currentTime = new AtomicLong(0L);
TimeProvider timeProvider = TimeProviderUtils.create(() -> currentTime.addAndGet(eachIterationDuration));
// Some runs of this test try to simulate a long desired balance computation. Setting a high value on the following setting
// prevents interrupting a long computation.
var clusterSettings = createBuiltInClusterSettings(
Settings.builder().put(DesiredBalanceComputer.MAX_BALANCE_COMPUTATION_TIME_DURING_INDEX_CREATION_SETTING.getKey(), "2m").build()
);
var desiredBalanceComputer = new DesiredBalanceComputer(clusterSettings, timeProvider, new ShardsAllocator() {
@Override
public void allocate(RoutingAllocation allocation) {
final var unassignedIterator = allocation.routingNodes().unassigned().iterator();
while (unassignedIterator.hasNext()) {
final var shardRouting = unassignedIterator.next();
if (shardRouting.primary()) {
unassignedIterator.initialize("node-0", null, 0L, allocation.changes());
} else {
unassignedIterator.removeAndIgnore(UnassignedInfo.AllocationStatus.NO_ATTEMPT, allocation.changes());
}
}
// move shard on each iteration
for (var shard : allocation.routingNodes().node("node-0").shardsWithState(STARTED).toList()) {
allocation.routingNodes().relocateShard(shard, "node-1", 0L, "test", allocation.changes());
}
for (var shard : allocation.routingNodes().node("node-1").shardsWithState(STARTED).toList()) {
allocation.routingNodes().relocateShard(shard, "node-0", 0L, "test", allocation.changes());
}
}
@Override
public ShardAllocationDecision explainShardAllocation(ShardRouting shard, RoutingAllocation allocation) {
throw new AssertionError("only used for allocation explain");
}
}, TEST_ONLY_EXPLAINER);
assertLoggerExpectationsFor(() -> {
var iteration = new AtomicInteger(0);
desiredBalanceComputer.compute(
DesiredBalance.BECOME_MASTER_INITIAL,
createInput(createInitialClusterState(3)),
queue(),
input -> iteration.incrementAndGet() < iterations
);
}, expectation);
}
private void assertLoggerExpectationsFor(Runnable action, MockLog.LoggingExpectation... expectations) {
assertThatLogger(action, DesiredBalanceComputer.class, expectations);
}
public void testLoggingOfComputeCallsAndIterationsSinceConvergence() {
final var clusterSettings = new ClusterSettings(
Settings.builder().put(DesiredBalanceComputer.PROGRESS_LOG_INTERVAL_SETTING.getKey(), TimeValue.timeValueMillis(5L)).build(),
ClusterSettings.BUILT_IN_CLUSTER_SETTINGS
);
final var timeInMillis = new AtomicLong(-1L);
final var iterationCounter = new AtomicInteger(0);
final var requiredIterations = new AtomicInteger(2);
final var desiredBalance = new AtomicReference<DesiredBalance>(DesiredBalance.BECOME_MASTER_INITIAL);
final var indexSequence = new AtomicLong(0);
final var clusterState = createInitialClusterState(1, 1, 0);
final var computer = new DesiredBalanceComputer(
clusterSettings,
TimeProviderUtils.create(timeInMillis::incrementAndGet),
new BalancedShardsAllocator(Settings.EMPTY),
TEST_ONLY_EXPLAINER
) {
@Override
boolean hasEnoughIterations(int currentIteration) {
iterationCounter.incrementAndGet();
return currentIteration >= requiredIterations.get();
}
};
computer.setConvergenceLogMsgLevel(Level.INFO);
record ExpectedLastConvergenceInfo(int numComputeCalls, int numTotalIterations, long timestampMillis) {}
Consumer<ExpectedLastConvergenceInfo> assertLastConvergenceInfo = data -> {
assertEquals(data.numComputeCalls(), computer.getNumComputeCallsSinceLastConverged());
assertEquals(data.numTotalIterations(), computer.getNumIterationsSinceLastConverged());
assertEquals(data.timestampMillis(), computer.getLastConvergedTimeMillis());
};
final Function<Predicate<DesiredBalanceInput>, Runnable> getComputeRunnableForIsFreshPredicate = isFreshFunc -> {
final var input = new DesiredBalanceInput(indexSequence.incrementAndGet(), routingAllocationOf(clusterState), List.of());
return () -> desiredBalance.set(computer.compute(desiredBalance.get(), input, queue(), isFreshFunc));
};
record LogExpectationData(
boolean isConverged,
String timeSinceConverged,
int totalIterations,
int totalComputeCalls,
int currentIterations,
String currentDuration
) {
LogExpectationData(boolean isConverged, String timeSinceConverged, int totalIterations) {
this(isConverged, timeSinceConverged, totalIterations, 0, 0, "");
}
}
Function<LogExpectationData, MockLog.SeenEventExpectation> getLogExpectation = data -> {
final var singleComputeCallMsg = "Desired balance computation for [%d] "
+ (data.isConverged ? "" : "is still not ")
+ "converged after [%s] and [%d] iterations";
return new MockLog.SeenEventExpectation(
"expected a " + (data.isConverged ? "converged" : "not converged") + " log message",
DesiredBalanceComputer.class.getCanonicalName(),
Level.INFO,
(data.totalComputeCalls > 1
? Strings.format(
singleComputeCallMsg + ", resumed computation [%d] times with [%d] iterations since the last resumption [%s] ago",
indexSequence.get(),
data.timeSinceConverged,
data.totalIterations,
data.totalComputeCalls,
data.currentIterations,
data.currentDuration
)
: Strings.format(singleComputeCallMsg, indexSequence.get(), data.timeSinceConverged, data.totalIterations))
);
};
final Consumer<DesiredBalance.ComputationFinishReason> assertFinishReason = reason -> {
assertEquals(reason, desiredBalance.get().finishReason());
if (DesiredBalance.ComputationFinishReason.CONVERGED == reason) {
// Verify the number of compute() calls and total iterations have been reset after converging.
assertLastConvergenceInfo.accept(new ExpectedLastConvergenceInfo(0, 0, timeInMillis.get()));
}
};
// No compute() calls yet, last convergence timestamp is the startup time.
assertLastConvergenceInfo.accept(new ExpectedLastConvergenceInfo(0, 0, timeInMillis.get()));
// Converges right away, verify the debug level convergence message.
assertLoggerExpectationsFor(
getComputeRunnableForIsFreshPredicate.apply(ignored -> true),
getLogExpectation.apply(new LogExpectationData(true, "3ms", 2))
);
assertFinishReason.accept(DesiredBalance.ComputationFinishReason.CONVERGED);
final var lastConvergenceTimestampMillis = computer.getLastConvergedTimeMillis();
// Test a series of compute() calls that don't converge.
iterationCounter.set(0);
requiredIterations.set(10);
// This INFO is triggered from the interval since last convergence timestamp.
assertLoggerExpectationsFor(
getComputeRunnableForIsFreshPredicate.apply(ignored -> iterationCounter.get() < 6),
getLogExpectation.apply(new LogExpectationData(false, "5ms", 4))
);
assertFinishReason.accept(DesiredBalance.ComputationFinishReason.YIELD_TO_NEW_INPUT);
assertLastConvergenceInfo.accept(new ExpectedLastConvergenceInfo(1, 6, lastConvergenceTimestampMillis));
iterationCounter.set(0);
// The next INFO is triggered from the interval since last INFO message logged, and then another after the interval period.
assertLoggerExpectationsFor(
getComputeRunnableForIsFreshPredicate.apply(ignored -> iterationCounter.get() < 8),
getLogExpectation.apply(new LogExpectationData(false, "10ms", 8, 2, 2, "2ms")),
getLogExpectation.apply(new LogExpectationData(false, "15ms", 13, 2, 7, "7ms"))
);
assertFinishReason.accept(DesiredBalance.ComputationFinishReason.YIELD_TO_NEW_INPUT);
assertLastConvergenceInfo.accept(new ExpectedLastConvergenceInfo(2, 14, lastConvergenceTimestampMillis));
assertLoggerExpectationsFor(
getComputeRunnableForIsFreshPredicate.apply(ignored -> true),
getLogExpectation.apply(new LogExpectationData(false, "20ms", 17, 3, 3, "3ms")),
getLogExpectation.apply(new LogExpectationData(false, "25ms", 22, 3, 8, "8ms")),
getLogExpectation.apply(new LogExpectationData(true, "27ms", 24, 3, 10, "10ms"))
);
assertFinishReason.accept(DesiredBalance.ComputationFinishReason.CONVERGED);
// First INFO is triggered from interval since last converged, second is triggered from the inverval since the last INFO log.
assertLoggerExpectationsFor(
getComputeRunnableForIsFreshPredicate.apply(ignored -> true),
getLogExpectation.apply(new LogExpectationData(false, "5ms", 4)),
getLogExpectation.apply(new LogExpectationData(false, "10ms", 9)),
getLogExpectation.apply(new LogExpectationData(true, "11ms", 10))
);
assertFinishReason.accept(DesiredBalance.ComputationFinishReason.CONVERGED);
// Verify the final assignment mappings after converging.
final var index = clusterState.metadata().getProject(Metadata.DEFAULT_PROJECT_ID).index(TEST_INDEX).getIndex();
final var expectedAssignmentsMap = Map.of(new ShardId(index, 0), new ShardAssignment(Set.of("node-0"), 1, 0, 0));
assertDesiredAssignments(desiredBalance.get(), expectedAssignmentsMap);
}
@TestLogging(
value = "org.elasticsearch.cluster.routing.allocation.allocator.DesiredBalanceComputer.allocation_explain:DEBUG",
reason = "test logging for allocation explain"
)
public void testLogAllocationExplainForUnassigned() {
final ClusterSettings clusterSettings = createBuiltInClusterSettings();
final var computer = new DesiredBalanceComputer(
clusterSettings,
TimeProviderUtils.create(() -> 0L),
new BalancedShardsAllocator(Settings.EMPTY),
createAllocationService()::explainShardAllocation
);
final String loggerName = DesiredBalanceComputer.class.getCanonicalName() + ".allocation_explain";
// No logging since no unassigned shard
{
final var allocation = new RoutingAllocation(
randomAllocationDeciders(Settings.EMPTY, clusterSettings),
createInitialClusterState(1, 1, 0),
ClusterInfo.EMPTY,
SnapshotShardSizeInfo.EMPTY,
0L
);
try (var mockLog = MockLog.capture(loggerName)) {
mockLog.addExpectation(
new MockLog.UnseenEventExpectation(
"Should NOT log allocation explain since all shards are assigned",
loggerName,
Level.DEBUG,
"*"
)
);
computer.compute(DesiredBalance.BECOME_MASTER_INITIAL, DesiredBalanceInput.create(1, allocation), queue(), ignore -> true);
mockLog.assertAllExpectationsMatched();
}
}
var initialState = createInitialClusterState(1, 1, 1);
// Logging for unassigned primary shard (preferred over unassigned replica)
{
final DiscoveryNode dataNode = initialState.nodes().getDataNodes().values().iterator().next();
final var clusterState = initialState.copyAndUpdateMetadata(
b -> b.putCustom(
NodesShutdownMetadata.TYPE,
new NodesShutdownMetadata(
Map.of(
dataNode.getId(),
SingleNodeShutdownMetadata.builder()
.setNodeId(dataNode.getId())
.setType(SingleNodeShutdownMetadata.Type.REMOVE)
.setReason("test")
.setStartedAtMillis(0L)
.build()
)
)
)
);
final var allocation = new RoutingAllocation(
randomAllocationDeciders(Settings.EMPTY, clusterSettings),
clusterState,
ClusterInfo.EMPTY,
SnapshotShardSizeInfo.EMPTY,
0L
);
final DesiredBalance newDesiredBalance;
try (var mockLog = MockLog.capture(loggerName)) {
mockLog.addExpectation(
new MockLog.SeenEventExpectation(
"Should log allocation explain for unassigned primary shard",
loggerName,
Level.DEBUG,
"*unassigned shard [[test-index][0], node[null], [P], * due to allocation decision *"
+ "\"decider\":\"node_shutdown\",\"decision\":\"NO\"*"
)
);
newDesiredBalance = computer.compute(
DesiredBalance.BECOME_MASTER_INITIAL,
DesiredBalanceInput.create(1, allocation),
queue(),
ignore -> true
);
mockLog.assertAllExpectationsMatched();
}
// No logging since the same tracked primary is still unassigned
try (var mockLog = MockLog.capture(loggerName)) {
mockLog.addExpectation(
new MockLog.UnseenEventExpectation(
"Should NOT log allocation explain again for existing tracked unassigned shard",
loggerName,
Level.DEBUG,
"*"
)
);
computer.compute(newDesiredBalance, DesiredBalanceInput.create(2, allocation), queue(), ignore -> true);
mockLog.assertAllExpectationsMatched();
}
}
// Logging for unassigned replica shard (since primary is now assigned)
{
final var allocation = new RoutingAllocation(
randomAllocationDeciders(Settings.EMPTY, clusterSettings),
initialState,
ClusterInfo.EMPTY,
SnapshotShardSizeInfo.EMPTY,
0L
);
try (var mockLog = MockLog.capture(loggerName)) {
mockLog.addExpectation(
new MockLog.SeenEventExpectation(
"Should log for previously unassigned shard becomes assigned",
loggerName,
Level.DEBUG,
"*assigned previously tracked unassigned shard [[test-index][0], node[null], [P],*"
)
);
mockLog.addExpectation(
new MockLog.SeenEventExpectation(
"Should log allocation explain for unassigned replica shard",
loggerName,
Level.DEBUG,
"*unassigned shard [[test-index][0], node[null], [R], * due to allocation decision *"
+ "\"decider\":\"same_shard\",\"decision\":\"NO\"*"
)
);
computer.compute(DesiredBalance.BECOME_MASTER_INITIAL, DesiredBalanceInput.create(1, allocation), queue(), ignore -> true);
mockLog.assertAllExpectationsMatched();
}
}
// No logging if master is shutting down
{
var clusterState = createInitialClusterState(1, 1, 1).copyAndUpdateMetadata(
b -> b.putCustom(
NodesShutdownMetadata.TYPE,
new NodesShutdownMetadata(
Map.of(
"master",
SingleNodeShutdownMetadata.builder()
.setNodeId("master")
.setType(SingleNodeShutdownMetadata.Type.SIGTERM)
.setReason("test")
.setStartedAtMillis(0L)
.setGracePeriod(TimeValue.THIRTY_SECONDS)
.build()
)
)
)
);
final var allocation = new RoutingAllocation(
randomAllocationDeciders(Settings.EMPTY, clusterSettings),
clusterState,
ClusterInfo.EMPTY,
SnapshotShardSizeInfo.EMPTY,
0L
);
try (var mockLog = MockLog.capture(loggerName)) {
mockLog.addExpectation(
new MockLog.UnseenEventExpectation(
"Should NOT log allocation explain since all shards are assigned",
loggerName,
Level.DEBUG,
"*"
)
);
computer.compute(DesiredBalance.BECOME_MASTER_INITIAL, DesiredBalanceInput.create(1, allocation), queue(), ignore -> true);
mockLog.assertAllExpectationsMatched();
}
}
}
public void testMaybeSimulateAlreadyStartedShards() {
final var clusterInfoSimulator = mock(ClusterInfoSimulator.class);
final var routingChangesObserver = mock(RoutingChangesObserver.class);
final ClusterState initialState = createInitialClusterState(3, 3, 1);
final RoutingNodes routingNodes = initialState.mutableRoutingNodes();
final IndexRoutingTable indexRoutingTable = initialState.routingTable(ProjectId.DEFAULT).index(TEST_INDEX);
final List<ShardRouting> existingStartedShards = new ArrayList<>();
// Shard 0 - primary started
final String shard0PrimaryNodeId = randomFrom(initialState.nodes().getDataNodes().values()).getId();
existingStartedShards.add(
routingNodes.startShard(
routingNodes.initializeShard(
indexRoutingTable.shard(0).primaryShard(),
shard0PrimaryNodeId,
null,
randomLongBetween(100, 999),
routingChangesObserver
),
routingChangesObserver,
randomLongBetween(100, 999)
)
);
if (randomBoolean()) {
existingStartedShards.add(
routingNodes.startShard(
routingNodes.initializeShard(
indexRoutingTable.shard(0).replicaShards().getFirst(),
randomValueOtherThan(shard0PrimaryNodeId, () -> randomFrom(initialState.nodes().getDataNodes().values()).getId()),
null,
randomLongBetween(100, 999),
routingChangesObserver
),
routingChangesObserver,
randomLongBetween(100, 999)
)
);
}
// Shard 1 - initializing primary or replica
final String shard1PrimaryNodeId = randomFrom(initialState.nodes().getDataNodes().values()).getId();
ShardRouting initializingShard = routingNodes.initializeShard(
indexRoutingTable.shard(1).primaryShard(),
shard1PrimaryNodeId,
null,
randomLongBetween(100, 999),
routingChangesObserver
);
if (randomBoolean()) {
existingStartedShards.add(routingNodes.startShard(initializingShard, routingChangesObserver, randomLongBetween(100, 999)));
initializingShard = routingNodes.initializeShard(
indexRoutingTable.shard(1).replicaShards().getFirst(),
randomValueOtherThan(shard1PrimaryNodeId, () -> randomFrom(initialState.nodes().getDataNodes().values()).getId()),
null,
randomLongBetween(100, 999),
routingChangesObserver
);
}
// Shard 2 - Relocating primary
final String shard2PrimaryNodeId = randomFrom(initialState.nodes().getDataNodes().values()).getId();
final Tuple<ShardRouting, ShardRouting> relocationTuple = routingNodes.relocateShard(
routingNodes.startShard(
routingNodes.initializeShard(
indexRoutingTable.shard(2).primaryShard(),
shard2PrimaryNodeId,
null,
randomLongBetween(100, 999),
routingChangesObserver
),
routingChangesObserver,
randomLongBetween(100, 999)
),
randomValueOtherThan(shard2PrimaryNodeId, () -> randomFrom(initialState.nodes().getDataNodes().values()).getId()),
randomLongBetween(100, 999),
"test",
routingChangesObserver
);
existingStartedShards.add(relocationTuple.v1());
final ClusterInfo clusterInfo = ClusterInfo.builder()
.dataPath(
existingStartedShards.stream()
.collect(Collectors.toUnmodifiableMap(NodeAndShard::from, ignore -> "/data/" + randomIdentifier()))
)
.build();
// No extra simulation calls since there is no new shard or relocated shard that are not in ClusterInfo
{
DesiredBalanceComputer.maybeSimulateAlreadyStartedShards(clusterInfo, routingNodes, clusterInfoSimulator);
verifyNoInteractions(clusterInfoSimulator);
}
// Start the initializing shard and it should be identified and simulated
final var startedShard = routingNodes.startShard(initializingShard, routingChangesObserver, randomLongBetween(100, 999));
{
DesiredBalanceComputer.maybeSimulateAlreadyStartedShards(clusterInfo, routingNodes, clusterInfoSimulator);
verify(clusterInfoSimulator).simulateAlreadyStartedShard(startedShard, null);
verifyNoMoreInteractions(clusterInfoSimulator);
}
// Also start the relocating shard and both should be identified and simulated
{
Mockito.clearInvocations(clusterInfoSimulator);
final var startedRelocatingShard = routingNodes.startShard(
relocationTuple.v2(),
routingChangesObserver,
randomLongBetween(100, 999)
);
DesiredBalanceComputer.maybeSimulateAlreadyStartedShards(clusterInfo, routingNodes, clusterInfoSimulator);
verify(clusterInfoSimulator).simulateAlreadyStartedShard(startedShard, null);
verify(clusterInfoSimulator).simulateAlreadyStartedShard(startedRelocatingShard, relocationTuple.v1().currentNodeId());
verifyNoMoreInteractions(clusterInfoSimulator);
}
}
private static ShardRouting findShard(ClusterState clusterState, String name, boolean primary) {
final var indexShardRoutingTable = clusterState.getRoutingTable().index(name).shard(0);
return primary ? indexShardRoutingTable.primaryShard() : indexShardRoutingTable.replicaShards().getFirst();
}
private static ShardId findShardId(ClusterState clusterState, String name) {
return clusterState.getRoutingTable().index(name).shard(0).shardId();
}
static ClusterState createInitialClusterState(int dataNodesCount) {
return createInitialClusterState(dataNodesCount, 2, 1);
}
static ClusterState createInitialClusterState(int dataNodesCount, int numShards, int numReplicas) {
var discoveryNodes = DiscoveryNodes.builder().add(newNode("master", Set.of(DiscoveryNodeRole.MASTER_ROLE)));
for (int i = 0; i < dataNodesCount; i++) {
discoveryNodes.add(newNode("node-" + i, Set.of(DiscoveryNodeRole.DATA_ROLE)));
}
var indexMetadata = IndexMetadata.builder(TEST_INDEX)
.settings(indexSettings(IndexVersion.current(), numShards, numReplicas))
.build();
return ClusterState.builder(ClusterName.DEFAULT)
.nodes(discoveryNodes.masterNodeId("master").localNodeId("master"))
.metadata(Metadata.builder().put(indexMetadata, true))
.routingTable(RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY).addAsNew(indexMetadata))
.build();
}
static ClusterState mutateAllocationStatuses(ClusterState clusterState) {
final var routingTableBuilder = RoutingTable.builder();
for (final var indexRoutingTable : clusterState.routingTable()) {
final var indexRoutingTableBuilder = IndexRoutingTable.builder(indexRoutingTable.getIndex());
for (int shardId = 0; shardId < indexRoutingTable.size(); shardId++) {
final var shardRoutingTable = indexRoutingTable.shard(shardId);
final var shardRoutingTableBuilder = new IndexShardRoutingTable.Builder(shardRoutingTable.shardId());
for (int shardCopy = 0; shardCopy < shardRoutingTable.size(); shardCopy++) {
shardRoutingTableBuilder.addShard(mutateAllocationStatus(shardRoutingTable.shard(shardCopy)));
}
indexRoutingTableBuilder.addIndexShard(shardRoutingTableBuilder);
}
routingTableBuilder.add(indexRoutingTableBuilder);
}
return ClusterState.builder(clusterState).routingTable(routingTableBuilder).build();
}
private static ShardRouting mutateAllocationStatus(ShardRouting shardRouting) {
if (shardRouting.unassigned()) {
var unassignedInfo = shardRouting.unassignedInfo();
return shardRouting.updateUnassigned(
new UnassignedInfo(
unassignedInfo.reason(),
unassignedInfo.message(),
unassignedInfo.failure(),
unassignedInfo.failedAllocations(),
unassignedInfo.unassignedTimeNanos(),
unassignedInfo.unassignedTimeMillis(),
unassignedInfo.delayed(),
randomFrom(
UnassignedInfo.AllocationStatus.DECIDERS_NO,
UnassignedInfo.AllocationStatus.NO_ATTEMPT,
UnassignedInfo.AllocationStatus.DECIDERS_THROTTLED
),
unassignedInfo.failedNodeIds(),
unassignedInfo.lastAllocatedNodeId()
),
shardRouting.recoverySource()
);
} else {
return shardRouting;
}
}
/**
* @return a {@link DesiredBalanceComputer} which allocates unassigned primaries to node-0 and unassigned replicas to node-1
*/
private static DesiredBalanceComputer createDesiredBalanceComputer() {
return createDesiredBalanceComputer(new ShardsAllocator() {
@Override
public void allocate(RoutingAllocation allocation) {
final var unassignedIterator = allocation.routingNodes().unassigned().iterator();
while (unassignedIterator.hasNext()) {
final var shardRouting = unassignedIterator.next();
if (shardRouting.primary()) {
unassignedIterator.initialize("node-0", null, 0L, allocation.changes());
} else if (isCorrespondingPrimaryStarted(shardRouting, allocation)) {
unassignedIterator.initialize("node-1", null, 0L, allocation.changes());
} else {
unassignedIterator.removeAndIgnore(UnassignedInfo.AllocationStatus.NO_ATTEMPT, allocation.changes());
}
}
}
private static boolean isCorrespondingPrimaryStarted(ShardRouting shardRouting, RoutingAllocation allocation) {
return allocation.routingNodes().assignedShards(shardRouting.shardId()).stream().anyMatch(r -> r.primary() && r.started());
}
@Override
public ShardAllocationDecision explainShardAllocation(ShardRouting shard, RoutingAllocation allocation) {
throw new AssertionError("only used for allocation explain");
}
});
}
private static DesiredBalanceComputer createDesiredBalanceComputer(ShardsAllocator allocator) {
return new DesiredBalanceComputer(
createBuiltInClusterSettings(),
TimeProviderUtils.create(() -> 0L),
allocator,
TEST_ONLY_EXPLAINER
);
}
private static void assertDesiredAssignments(DesiredBalance desiredBalance, Map<ShardId, ShardAssignment> expected) {
assertThat(desiredBalance.assignments(), equalTo(expected));
}
private static DesiredBalanceInput createInput(ClusterState clusterState, ShardRouting... ignored) {
return new DesiredBalanceInput(randomInt(), routingAllocationOf(clusterState), List.of(ignored));
}
private static RoutingAllocation routingAllocationOf(ClusterState clusterState) {
return new RoutingAllocation(new AllocationDeciders(List.of()), clusterState, ClusterInfo.EMPTY, SnapshotShardSizeInfo.EMPTY, 0L);
}
private static RoutingAllocation routingAllocationWithDecidersOf(
ClusterState clusterState,
ClusterInfo clusterInfo,
Settings settings
) {
return new RoutingAllocation(
randomAllocationDeciders(settings, createBuiltInClusterSettings(settings)),
clusterState,
clusterInfo,
SnapshotShardSizeInfo.EMPTY,
0L
);
}
private static Queue<List<MoveAllocationCommand>> queue(MoveAllocationCommand... commands) {
return new LinkedList<>(List.of(List.of(commands)));
}
}
|
ClusterInfoTestBuilder
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
|
{
"start": 64555,
"end": 64831
}
|
class ____ {}
Object quux = Collections.<emptyList>singleton(null);
}
""")
.doTest(TEXT_MATCH);
}
/** A {@link BugChecker} for testing. */
@BugPattern(summary = "RenameClassChecker", severity = ERROR)
public static
|
emptyList
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/util/ImmutableStreamGraph.java
|
{
"start": 1076,
"end": 1139
}
|
class ____ provides read-only StreamGraph. */
@Internal
public
|
that
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/annotatewith/deprecated/DeprecatedTest.java
|
{
"start": 763,
"end": 2182
}
|
class ____ {
@ProcessorTest
@WithClasses( { DeprecatedMapperWithMethod.class, CustomMethodOnlyAnnotation.class} )
public void deprecatedWithMethodCorrectCopy() throws NoSuchMethodException {
DeprecatedMapperWithMethod mapper = Mappers.getMapper( DeprecatedMapperWithMethod.class );
Method method = mapper.getClass().getMethod( "map", DeprecatedMapperWithMethod.Source.class );
Deprecated annotation = method.getAnnotation( Deprecated.class );
assertThat( annotation ).isNotNull();
}
@ProcessorTest
@WithClasses(DeprecatedMapperWithClass.class)
public void deprecatedWithClassCorrectCopy() {
DeprecatedMapperWithClass mapper = Mappers.getMapper( DeprecatedMapperWithClass.class );
Deprecated annotation = mapper.getClass().getAnnotation( Deprecated.class );
assertThat( annotation ).isNotNull();
}
@ProcessorTest
@WithClasses(RepeatDeprecatedMapper.class)
@ExpectedCompilationOutcome(
value = CompilationResult.SUCCEEDED,
diagnostics = {
@Diagnostic(
kind = javax.tools.Diagnostic.Kind.WARNING,
type = RepeatDeprecatedMapper.class,
message = "Annotation \"Deprecated\" is already present with the " +
"same elements configuration."
)
}
)
public void deprecatedWithRepeat() {
}
}
|
DeprecatedTest
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/output/IntegerOutput.java
|
{
"start": 1049,
"end": 1560
}
|
class ____<K, V> extends CommandOutput<K, V, Long> {
public IntegerOutput(RedisCodec<K, V> codec) {
super(codec, null);
}
@Override
public void set(long integer) {
output = integer;
}
@Override
public void set(ByteBuffer bytes) {
if (bytes == null) {
output = null;
} else {
// fallback for long as ByteBuffer
output = Long.parseLong(StandardCharsets.UTF_8.decode(bytes).toString());
}
}
}
|
IntegerOutput
|
java
|
apache__camel
|
components/camel-infinispan/camel-infinispan-embedded/src/main/java/org/apache/camel/component/infinispan/embedded/InfinispanEmbeddedEventListeners.java
|
{
"start": 1895,
"end": 2122
}
|
class ____ extends InfinispanEmbeddedEventListener {
public LocalAsync(Set<Event.Type> eventTypes) {
super(eventTypes);
}
}
@Listener(clustered = false, sync = true)
public static
|
LocalAsync
|
java
|
apache__kafka
|
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/rest/entities/WorkerStatus.java
|
{
"start": 998,
"end": 2977
}
|
class ____ {
private static final WorkerStatus HEALTHY = new WorkerStatus(
"healthy",
"Worker has completed startup and is ready to handle requests."
);
private final String status;
private final String message;
@JsonCreator
private WorkerStatus(
@JsonProperty("status") String status,
@JsonProperty("message") String message
) {
this.status = status;
this.message = message;
}
public static WorkerStatus healthy() {
return HEALTHY;
}
public static WorkerStatus starting(String statusDetails) {
String message = "Worker is still starting up.";
if (statusDetails != null)
message += " " + statusDetails;
return new WorkerStatus(
"starting",
message
);
}
public static WorkerStatus unhealthy(String statusDetails) {
String message = "Worker was unable to handle this request and may be unable to handle other requests.";
if (statusDetails != null)
message += " " + statusDetails;
return new WorkerStatus(
"unhealthy",
message
);
}
@JsonProperty
public String status() {
return status;
}
@JsonProperty
public String message() {
return message;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WorkerStatus that = (WorkerStatus) o;
return Objects.equals(status, that.status) && Objects.equals(message, that.message);
}
@Override
public int hashCode() {
return Objects.hash(status, message);
}
@Override
public String toString() {
return "WorkerStatus{" +
"status='" + status + '\'' +
", message='" + message + '\'' +
'}';
}
}
|
WorkerStatus
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/ExchangeRate.java
|
{
"start": 384,
"end": 1141
}
|
class ____ {
public ExchangeRate() {
super();
}
@Id @GeneratedValue
private Integer id;
@Column
private double rate;
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Embedded
private ExchangeRateKey key = new ExchangeRateKey();
public ExchangeRateKey getKey() {
return key;
}
public void setKey(ExchangeRateKey key) {
this.key = key;
}
@jakarta.persistence.ManyToOne(fetch = FetchType.LAZY )
private ExchangeOffice parent = null;
public ExchangeOffice getParent() {
return parent;
}
public void setParent(ExchangeOffice parent) {
this.parent = parent;
}
}
|
ExchangeRate
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/inheritance/tableperclass/Category.java
|
{
"start": 312,
"end": 347
}
|
class ____ extends Element {
}
|
Category
|
java
|
alibaba__nacos
|
client/src/main/java/com/alibaba/nacos/client/ai/utils/CacheKeyUtils.java
|
{
"start": 788,
"end": 1912
}
|
class ____ {
public static final String LATEST_VERSION = "latest";
/**
* Build mcp server versioned key.
*
* @param mcpName name of mcp server
* @param version version of mcp server, if version is blank or null, use latest version
* @return mcp server versioned key, pattern ${mcpName}::${version}
*/
public static String buildMcpServerKey(String mcpName, String version) {
return buildVersionedKey(mcpName, version);
}
/**
* Build AgentCard versioned key.
*
* @param agentName name of agent name
* @param version version of agent name, if version is blank or null, use latest version
* @return mcp server versioned key, pattern ${mcpName}::${version}
*/
public static String buildAgentCardKey(String agentName, String version) {
return buildVersionedKey(agentName, version);
}
private static String buildVersionedKey(String name, String version) {
if (StringUtils.isBlank(version)) {
version = LATEST_VERSION;
}
return name + "::" + version;
}
}
|
CacheKeyUtils
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.