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 | elastic__elasticsearch | modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/builders/MultiPointBuilderTests.java | {
"start": 755,
"end": 2888
} | class ____ extends AbstractShapeBuilderTestCase<MultiPointBuilder> {
public void testInvalidBuilderException() {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new MultiPointBuilder((List<Coordinate>) null));
assertEquals("cannot create point collection with empty set of points", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new MultiPointBuilder(new CoordinatesBuilder().build()));
assertEquals("cannot create point collection with empty set of points", e.getMessage());
// one point is minimum
new MultiPointBuilder(new CoordinatesBuilder().coordinate(0.0, 0.0).build());
}
@Override
protected MultiPointBuilder createTestShapeBuilder() {
return createRandomShape();
}
@Override
protected MultiPointBuilder createMutation(MultiPointBuilder original) throws IOException {
return mutate(original);
}
static MultiPointBuilder mutate(MultiPointBuilder original) throws IOException {
MultiPointBuilder mutation = copyShape(original);
Coordinate[] coordinates = original.coordinates(false);
if (coordinates.length > 0) {
Coordinate coordinate = randomFrom(coordinates);
if (randomBoolean()) {
if (coordinate.x != 0.0) {
coordinate.x = coordinate.x / 2;
} else {
coordinate.x = randomDoubleBetween(-180.0, 180.0, true);
}
} else {
if (coordinate.y != 0.0) {
coordinate.y = coordinate.y / 2;
} else {
coordinate.y = randomDoubleBetween(-90.0, 90.0, true);
}
}
} else {
coordinates = new Coordinate[] { new Coordinate(1.0, 1.0) };
}
return MultiPointBuilder.class.cast(mutation.coordinates(coordinates));
}
static MultiPointBuilder createRandomShape() {
return (MultiPointBuilder) RandomShapeGenerator.createShape(random(), ShapeType.MULTIPOINT);
}
}
| MultiPointBuilderTests |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/AutoValueBoxedValues.java | {
"start": 5524,
"end": 7753
} | class ____.
* @param state The visitor state.
* @param getters The {@link List} of {@link Getter} in the {@link AutoValue} class.
*/
private void handleSetterMethods(ClassTree classTree, VisitorState state, List<Getter> getters) {
// Identify and try to fix the setters.
classTree.getMembers().stream()
.filter(MethodTree.class::isInstance)
.map(memberTree -> (MethodTree) memberTree)
.filter(
methodTree ->
ABSTRACT_MATCHER.matches(methodTree, state)
&& methodTree.getParameters().size() == 1
&& isSameType(getType(methodTree.getReturnType()), getType(classTree), state))
.forEach(methodTree -> maybeFixSetter(methodTree, state, getters));
// Identify and try to fix the getters.
classTree.getMembers().stream()
.filter(MethodTree.class::isInstance)
.map(memberTree -> (MethodTree) memberTree)
.filter(
methodTree ->
ABSTRACT_MATCHER.matches(methodTree, state) && methodTree.getParameters().isEmpty())
.forEach(methodTree -> maybeFixGetterInBuilder(methodTree, state, getters));
}
/** Given a setter, it tries to apply a fix if the corresponding getter was also fixed. */
private void maybeFixSetter(MethodTree methodTree, VisitorState state, List<Getter> getters) {
if (isSuppressed(methodTree, state)) {
return;
}
boolean allGettersPrefixed = allGettersPrefixed(getters);
Optional<Getter> fixedGetter =
getters.stream()
.filter(
getter ->
!getter.fix().isEmpty()
&& matchGetterAndSetter(getter.method(), methodTree, allGettersPrefixed))
.findAny();
if (fixedGetter.isPresent()) {
var parameter = methodTree.getParameters().getFirst();
Type type = getType(parameter);
if (isBoxedPrimitive(state, type) && !hasNullableAnnotation(parameter)) {
suggestRemoveUnnecessaryBoxing(parameter.getType(), state, type, fixedGetter.get().fix());
}
}
}
/**
* Given a getter in the Builder class, it tries to apply a fix if the corresponding getter in the
* parent {@link AutoValue} | tree |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/sampler/DiversifiedNumericSamplerAggregator.java | {
"start": 1524,
"end": 2709
} | class ____ extends SamplerAggregator {
private ValuesSource.Numeric valuesSource;
private int maxDocsPerValue;
DiversifiedNumericSamplerAggregator(
String name,
int shardSize,
AggregatorFactories factories,
AggregationContext context,
Aggregator parent,
Map<String, Object> metadata,
ValuesSourceConfig valuesSourceConfig,
int maxDocsPerValue
) throws IOException {
super(name, shardSize, factories, context, parent, metadata);
assert valuesSourceConfig.hasValues();
this.valuesSource = (ValuesSource.Numeric) valuesSourceConfig.getValuesSource();
this.maxDocsPerValue = maxDocsPerValue;
}
@Override
public DeferringBucketCollector buildDeferringCollector() {
bdd = new DiverseDocsDeferringCollector(this::addRequestCircuitBreakerBytes);
return bdd;
}
/**
* A {@link DeferringBucketCollector} that identifies top scoring documents
* but de-duped by a key then passes only these on to nested collectors.
* This implementation is only for use with a single bucket aggregation.
*/
| DiversifiedNumericSamplerAggregator |
java | grpc__grpc-java | okhttp/src/test/java/io/grpc/okhttp/OkHttpClientTransportTest.java | {
"start": 100790,
"end": 101498
} | class ____ extends SocketFactory {
RuntimeException exception;
private RuntimeExceptionThrowingSocketFactory(RuntimeException exception) {
this.exception = exception;
}
@Override
public Socket createSocket(String s, int i) {
throw exception;
}
@Override
public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) {
throw exception;
}
@Override
public Socket createSocket(InetAddress inetAddress, int i) {
throw exception;
}
@Override
public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) {
throw exception;
}
}
static | RuntimeExceptionThrowingSocketFactory |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/foreach/ArrayProperties.java | {
"start": 835,
"end": 1219
} | class ____ implements Ordered {
private String name;
private final int index;
ArrayProperties(@Parameter Integer index) {
this.index = index;
}
@Override
public int getOrder() {
return index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| ArrayProperties |
java | netty__netty | common/src/test/java/io/netty/util/internal/TypeParameterMatcherTest.java | {
"start": 3842,
"end": 4334
} | class ____<E> { E a; }
@Test
public void testArrayAsTypeParam() throws Exception {
TypeParameterMatcher m = TypeParameterMatcher.find(new U<byte[]>() { }, U.class, "E");
assertFalse(m.match(new Object()));
assertTrue(m.match(new byte[1]));
}
@Test
public void testRawType() throws Exception {
TypeParameterMatcher m = TypeParameterMatcher.find(new U() { }, U.class, "E");
assertTrue(m.match(new Object()));
}
private static | U |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/async/RingBufferLogEventHandler.java | {
"start": 1235,
"end": 1383
} | class ____ works with Disruptor 3.x.
* </p>
* @deprecated Only used internally, will be removed in the next major version.
*/
@Deprecated
public | only |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/dispatcher/Dispatcher.java | {
"start": 7005,
"end": 7313
} | class ____ the Dispatcher component. The Dispatcher component is responsible for receiving
* job submissions, persisting them, spawning JobManagers to execute the jobs and to recover them in
* case of a master failure. Furthermore, it knows about the state of the Flink session cluster.
*/
public abstract | for |
java | quarkusio__quarkus | devtools/cli/src/main/java/io/quarkus/cli/image/Jib.java | {
"start": 943,
"end": 6792
} | class ____ extends BaseImageSubCommand {
private static final String JIB = "jib";
private static final String JIB_CONFIG_PREFIX = "quarkus.jib.";
private static final String BASE_JVM_IMAGE = "base-jvm-image";
private static final String JVM_ARGUMENTS = "jvm-arguments";
private static final String JVM_ENTRYPOINT = "jvm-entrypoint";
private static final String BASE_NATIVE_IMAGE = "base-native-image";
private static final String NATIVE_ARGUMENTS = "native-arguments";
private static final String NATIVE_ENTRYPOINT = "native-entrypoint";
private static final String LABELS = "labels.";
private static final String ENV_VARS = "environment-varialbes.";
private static final String PORTS = "ports";
private static final String PLATFORMS = "platforms";
private static final String IMAGE_DIGEST_FILE = "image-digest-file";
private static final String IMAGE_ID_FILE = "image-id-file";
private static final String OFFLINE_MODE = "offline-mode";
private static final String USER = "user";
@CommandLine.Option(order = 7, names = { "--base-image" }, description = "The base image to use.")
public Optional<String> baseImage;
@CommandLine.Option(order = 8, names = {
"--arg" }, description = "Additional argument to pass when starting the application.")
public List<String> arguments = new ArrayList<>();
@CommandLine.Option(order = 9, names = { "--entrypoint" }, description = "The entrypoint of the container image.")
public List<String> entrypoint = new ArrayList<>();
@CommandLine.Option(order = 10, names = { "--env" }, description = "Environment variables to add to the container image.")
public Map<String, String> environmentVariables = new HashMap<>();
@CommandLine.Option(order = 11, names = { "--label" }, description = "Custom labels to add to the generated image.")
public Map<String, String> labels = new HashMap<>();
@CommandLine.Option(order = 12, names = { "--port" }, description = "The ports to expose.")
public List<Integer> ports = new ArrayList<>();
@CommandLine.Option(order = 13, names = { "--user" }, description = "The user in the generated image.")
public String user;
@CommandLine.Option(order = 14, names = {
"--always-cache-base-image" }, description = "Controls the optimization which skips downloading base image layers that exist in a target registry.")
public boolean alwaysCacheBaseImage;
@CommandLine.Option(order = 15, names = {
"--platform" }, description = "The target platforms defined using the pattern <os>[/arch][/variant]|<os>/<arch>[/variant]")
public Set<String> platforms = new HashSet<>();
@CommandLine.Option(order = 16, names = {
"--image-digest-file" }, description = "The path of a file that will be written containing the digest of the generated image.")
public String imageDigestFile;
@CommandLine.Option(order = 17, names = {
"--image-id-file" }, description = "The path of a file that will be written containing the id of the generated image.")
public String imageIdFile;
@Override
public void populateContext(BuildToolContext context) {
super.populateContext(context);
Map<String, String> properties = context.getPropertiesOptions().properties;
properties.put(QUARKUS_CONTAINER_IMAGE_BUILDER, JIB);
baseImage.ifPresent(
d -> properties.put(
JIB_CONFIG_PREFIX + (context.getBuildOptions().buildNative ? BASE_NATIVE_IMAGE : BASE_JVM_IMAGE),
d));
if (!arguments.isEmpty()) {
String joinedArgs = arguments.stream().collect(Collectors.joining(","));
properties.put(JIB_CONFIG_PREFIX + (context.getBuildOptions().buildNative ? NATIVE_ARGUMENTS : JVM_ARGUMENTS),
joinedArgs);
}
if (!entrypoint.isEmpty()) {
String joinedEntrypoint = entrypoint.stream().collect(Collectors.joining(","));
properties.put(JIB_CONFIG_PREFIX + (context.getBuildOptions().buildNative ? NATIVE_ENTRYPOINT : JVM_ENTRYPOINT),
joinedEntrypoint);
}
if (!environmentVariables.isEmpty()) {
environmentVariables.forEach((key, value) -> {
properties.put(JIB_CONFIG_PREFIX + ENV_VARS + key, value);
});
}
if (!labels.isEmpty()) {
labels.forEach((key, value) -> {
properties.put(JIB_CONFIG_PREFIX + LABELS + key, value);
});
}
if (!ports.isEmpty()) {
String joinedPorts = ports.stream().map(String::valueOf).collect(Collectors.joining(","));
properties.put(JIB_CONFIG_PREFIX + PORTS, joinedPorts);
}
if (!platforms.isEmpty()) {
String joinedPlatforms = platforms.stream().collect(Collectors.joining(","));
properties.put(JIB_CONFIG_PREFIX + PLATFORMS, joinedPlatforms);
}
if (user != null && !user.isEmpty()) {
properties.put(JIB_CONFIG_PREFIX + USER, user);
}
if (imageDigestFile != null && !imageDigestFile.isEmpty()) {
properties.put(JIB_CONFIG_PREFIX + IMAGE_DIGEST_FILE, imageDigestFile);
}
if (imageIdFile != null && !imageIdFile.isEmpty()) {
properties.put(JIB_CONFIG_PREFIX + IMAGE_ID_FILE, imageIdFile);
}
if (context.getBuildOptions().offline) {
properties.put(JIB_CONFIG_PREFIX + OFFLINE_MODE, "true");
}
context.getForcedExtensions().add(QUARKUS_CONTAINER_IMAGE_EXTENSION_KEY_PREFIX + JIB);
}
@Override
public String toString() {
return "Jib {imageOptions='" + imageOptions + "', baseImage:'" + baseImage.orElse("<none>") + "'}";
}
}
| Jib |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssembler.java | {
"start": 2215,
"end": 4668
} | class ____ extends AbstractConfigurableMBeanInfoAssembler {
private @Nullable Set<String> ignoredMethods;
private @Nullable Map<String, Set<String>> ignoredMethodMappings;
/**
* Set the array of method names to be <b>ignored</b> when creating the management info.
* <p>These method names will be used for a bean if no entry corresponding to
* that bean is found in the {@code ignoredMethodsMappings} property.
* @see #setIgnoredMethodMappings(java.util.Properties)
*/
public void setIgnoredMethods(String... ignoredMethodNames) {
this.ignoredMethods = Set.of(ignoredMethodNames);
}
/**
* Set the mappings of bean keys to a comma-separated list of method names.
* <p>These method names are <b>ignored</b> when creating the management interface.
* <p>The property key must match the bean key and the property value must match
* the list of method names. When searching for method names to ignore for a bean,
* Spring will check these mappings first.
*/
public void setIgnoredMethodMappings(Properties mappings) {
this.ignoredMethodMappings = new HashMap<>();
for (Enumeration<?> en = mappings.keys(); en.hasMoreElements();) {
String beanKey = (String) en.nextElement();
String[] methodNames = StringUtils.commaDelimitedListToStringArray(mappings.getProperty(beanKey));
this.ignoredMethodMappings.put(beanKey, Set.of(methodNames));
}
}
@Override
protected boolean includeReadAttribute(Method method, String beanKey) {
return isNotIgnored(method, beanKey);
}
@Override
protected boolean includeWriteAttribute(Method method, String beanKey) {
return isNotIgnored(method, beanKey);
}
@Override
protected boolean includeOperation(Method method, String beanKey) {
return isNotIgnored(method, beanKey);
}
/**
* Determine whether the given method is supposed to be included,
* that is, not configured as to be ignored.
* @param method the operation method
* @param beanKey the key associated with the MBean in the beans map
* of the {@code MBeanExporter}
*/
protected boolean isNotIgnored(Method method, String beanKey) {
if (this.ignoredMethodMappings != null) {
Set<String> methodNames = this.ignoredMethodMappings.get(beanKey);
if (methodNames != null) {
return !methodNames.contains(method.getName());
}
}
if (this.ignoredMethods != null) {
return !this.ignoredMethods.contains(method.getName());
}
return true;
}
}
| MethodExclusionMBeanInfoAssembler |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/spi/EmbeddableInstantiator.java | {
"start": 423,
"end": 578
} | interface ____ extends Instantiator {
/**
* Create an instance of the embeddable
*/
Object instantiate(ValueAccess valueAccess);
}
| EmbeddableInstantiator |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/wiring/DisabledConnectorAttachmentOutgoingTest.java | {
"start": 1102,
"end": 1825
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(MyDummyConnector.class, MySource.class))
.overrideConfigKey("quarkus.messaging.auto-connector-attachment", "false");
@Inject
@Connector("dummy")
MyDummyConnector connector;
@Inject
MySource source;
@Test
public void testAutoAttachmentOfOutgoingChannel() {
assertThatThrownBy(() -> source.generate())
.hasCauseInstanceOf(DefinitionException.class);
}
@ApplicationScoped
@Connector("dummy")
static | DisabledConnectorAttachmentOutgoingTest |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/StringMatchResult.java | {
"start": 938,
"end": 1720
} | class ____ {
private final String matchString;
private final List<MatchedPosition> matches;
private final long len;
/**
* Creates new {@link StringMatchResult}.
*
* @param matchString
* @param matches
* @param len
*/
public StringMatchResult(String matchString, List<MatchedPosition> matches, long len) {
this.matchString = matchString;
this.matches = Collections.unmodifiableList(matches);
this.len = len;
}
public String getMatchString() {
return matchString;
}
public List<MatchedPosition> getMatches() {
return matches;
}
public long getLen() {
return len;
}
/**
* Match position in each string.
*/
public static | StringMatchResult |
java | spring-projects__spring-framework | spring-context-support/src/main/java/org/springframework/ui/freemarker/FreeMarkerConfigurationFactoryBean.java | {
"start": 1394,
"end": 1846
} | class ____ to specify just a "templateLoaderPath";
* you do not need any further configuration then. For example, in a web
* application context:
*
* <pre class="code"> <bean id="freemarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
* <property name="templateLoaderPath" value="/WEB-INF/freemarker/"/>
* </bean></pre>
*
* <p>See the {@link FreeMarkerConfigurationFactory} base | is |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/bean/BeanParameterThreeBodyOgnlTest.java | {
"start": 1141,
"end": 2085
} | class ____ extends ContextTestSupport {
@Test
public void testBeanParameterValue() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("3");
List<String> body = new ArrayList<>();
body.add("A");
body.add("B");
body.add("C");
template.sendBody("direct:start", body);
assertMockEndpointsSatisfied();
}
@Override
protected Registry createCamelRegistry() throws Exception {
Registry jndi = super.createCamelRegistry();
jndi.bind("foo", new MyBean());
return jndi;
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").to("bean:foo?method=bar(${body[0]},${body[1]},${body[2]})").to("mock:result");
}
};
}
public static | BeanParameterThreeBodyOgnlTest |
java | quarkusio__quarkus | independent-projects/bootstrap/maven-resolver/src/test/java/io/quarkus/bootstrap/resolver/maven/test/SplitLocalRepositoryTest.java | {
"start": 391,
"end": 1567
} | class ____ extends BootstrapMavenContextTestBase {
@Test
public void test() throws Exception {
BootstrapMavenContext mvn = bootstrapMavenContextForProject("custom-settings/split-local-repository");
LocalRepositoryManager lrm = mvn.getRepositorySystemSession().getLocalRepositoryManager();
assertEquals("installed/releases/foo/bar/1.0/bar-1.0.jar",
lrm.getPathForLocalArtifact(new DefaultArtifact("foo:bar:1.0")));
assertEquals("installed/snapshots/foo/bar/1.0-SNAPSHOT/bar-1.0-SNAPSHOT.jar",
lrm.getPathForLocalArtifact(new DefaultArtifact("foo:bar:1.0-SNAPSHOT")));
RemoteRepository remoteRepo = new RemoteRepository.Builder("remote-repo", "default", "https://example.com/repo/")
.build();
assertEquals("cached/releases/foo/bar/1.0/bar-1.0.jar",
lrm.getPathForRemoteArtifact(new DefaultArtifact("foo:bar:1.0"), remoteRepo, null));
assertEquals("cached/snapshots/foo/bar/1.0-SNAPSHOT/bar-1.0-SNAPSHOT.jar",
lrm.getPathForRemoteArtifact(new DefaultArtifact("foo:bar:1.0-SNAPSHOT"), remoteRepo, null));
}
}
| SplitLocalRepositoryTest |
java | redisson__redisson | redisson/src/main/java/org/redisson/cache/AbstractCacheMap.java | {
"start": 10031,
"end": 11300
} | class ____ extends AbstractSet<K> {
@Override
public Iterator<K> iterator() {
return new MapIterator<K>() {
@Override
public K next() {
if (mapEntry == null) {
throw new NoSuchElementException();
}
K key = mapEntry.getKey();
mapEntry = null;
return key;
}
@Override
public void remove() {
if (mapEntry == null) {
throw new IllegalStateException();
}
map.remove(mapEntry.getKey());
mapEntry = null;
}
};
}
@Override
public boolean contains(Object o) {
return AbstractCacheMap.this.containsKey(o);
}
@Override
public boolean remove(Object o) {
return AbstractCacheMap.this.remove(o) != null;
}
@Override
public int size() {
return AbstractCacheMap.this.size();
}
@Override
public void clear() {
AbstractCacheMap.this.clear();
}
}
final | KeySet |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/AnnotationsScannerTests.java | {
"start": 25860,
"end": 26010
} | class ____ implements GenericNonOverrideInterface<String> {
@TestAnnotation1
public void method(StringBuilder argument) {
}
}
| GenericNonOverride |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/slive/CreateOp.java | {
"start": 1763,
"end": 6443
} | class ____ extends Operation {
private static final Logger LOG = LoggerFactory.getLogger(CreateOp.class);
private static int DEF_IO_BUFFER_SIZE = 4096;
private static final String IO_BUF_CONFIG = ("io.file.buffer.size");
CreateOp(ConfigExtractor cfg, Random rnd) {
super(CreateOp.class.getSimpleName(), cfg, rnd);
}
/**
* Returns the block size to use (aligned to nearest BYTES_PER_CHECKSUM if
* configuration says a value exists) - this will avoid the warnings caused by
* this not occurring and the file will not be created if it is not correct...
*
* @return long
*/
private long determineBlockSize() {
Range<Long> blockSizeRange = getConfig().getBlockSize();
long blockSize = Range.betweenPositive(getRandom(), blockSizeRange);
Long byteChecksum = getConfig().getByteCheckSum();
if (byteChecksum == null) {
return blockSize;
}
// adjust to nearest multiple
long full = (blockSize / byteChecksum) * byteChecksum;
long toFull = blockSize - full;
if (toFull >= (byteChecksum / 2)) {
full += byteChecksum;
}
// adjust if over extended
if (full > blockSizeRange.getUpper()) {
full = blockSizeRange.getUpper();
}
if (full < blockSizeRange.getLower()) {
full = blockSizeRange.getLower();
}
return full;
}
/**
* Gets the replication amount
*
* @return short
*/
private short determineReplication() {
Range<Short> replicationAmountRange = getConfig().getReplication();
Range<Long> repRange = new Range<Long>(replicationAmountRange.getLower()
.longValue(), replicationAmountRange.getUpper().longValue());
short replicationAmount = (short) Range.betweenPositive(getRandom(),
repRange);
return replicationAmount;
}
/**
* Gets the output buffering size to use
*
* @return int
*/
private int getBufferSize() {
return getConfig().getConfig().getInt(IO_BUF_CONFIG, DEF_IO_BUFFER_SIZE);
}
/**
* Gets the file to create
*
* @return Path
*/
protected Path getCreateFile() {
Path fn = getFinder().getFile();
return fn;
}
@Override // Operation
List<OperationOutput> run(FileSystem fs) {
List<OperationOutput> out = super.run(fs);
FSDataOutputStream os = null;
try {
Path fn = getCreateFile();
Range<Long> writeSizeRange = getConfig().getWriteSize();
long writeSize = 0;
long blockSize = determineBlockSize();
short replicationAmount = determineReplication();
if (getConfig().shouldWriteUseBlockSize()) {
writeSizeRange = getConfig().getBlockSize();
}
writeSize = Range.betweenPositive(getRandom(), writeSizeRange);
long bytesWritten = 0;
long timeTaken = 0;
int bufSize = getBufferSize();
boolean overWrite = false;
DataWriter writer = new DataWriter(getRandom());
LOG.info("Attempting to create file at " + fn + " of size "
+ Helper.toByteInfo(writeSize) + " using blocksize "
+ Helper.toByteInfo(blockSize) + " and replication amount "
+ replicationAmount);
{
// open & create
long startTime = Timer.now();
os = fs.create(fn, overWrite, bufSize, replicationAmount, blockSize);
timeTaken += Timer.elapsed(startTime);
// write the given length
GenerateOutput stats = writer.writeSegment(writeSize, os);
bytesWritten += stats.getBytesWritten();
timeTaken += stats.getTimeTaken();
// capture close time
startTime = Timer.now();
os.close();
os = null;
timeTaken += Timer.elapsed(startTime);
}
LOG.info("Created file at " + fn + " of size "
+ Helper.toByteInfo(bytesWritten) + " bytes using blocksize "
+ Helper.toByteInfo(blockSize) + " and replication amount "
+ replicationAmount + " in " + timeTaken + " milliseconds");
// collect all the stats
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.OK_TIME_TAKEN, timeTaken));
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.BYTES_WRITTEN, bytesWritten));
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.SUCCESSES, 1L));
} catch (IOException e) {
out.add(new OperationOutput(OutputType.LONG, getType(),
ReportWriter.FAILURES, 1L));
LOG.warn("Error with creating", e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
LOG.warn("Error closing create stream", e);
}
}
}
return out;
}
}
| CreateOp |
java | netty__netty | codec-base/src/main/java/io/netty/handler/codec/MessageToMessageCodec.java | {
"start": 2226,
"end": 6125
} | class ____<INBOUND_IN, OUTBOUND_IN> extends ChannelDuplexHandler {
private final MessageToMessageDecoder<Object> decoder = new MessageToMessageDecoder<Object>(Object.class) {
@Override
public boolean acceptInboundMessage(Object msg) throws Exception {
return MessageToMessageCodec.this.acceptInboundMessage(msg);
}
@Override
@SuppressWarnings("unchecked")
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
MessageToMessageCodec.this.decode(ctx, (INBOUND_IN) msg, out);
}
@Override
public boolean isSharable() {
return MessageToMessageCodec.this.isSharable();
}
};
private final MessageToMessageEncoder<Object> encoder = new MessageToMessageEncoder<Object>(Object.class) {
@Override
public boolean acceptOutboundMessage(Object msg) throws Exception {
return MessageToMessageCodec.this.acceptOutboundMessage(msg);
}
@Override
@SuppressWarnings("unchecked")
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
MessageToMessageCodec.this.encode(ctx, (OUTBOUND_IN) msg, out);
}
@Override
public boolean isSharable() {
return MessageToMessageCodec.this.isSharable();
}
};
private final TypeParameterMatcher inboundMsgMatcher;
private final TypeParameterMatcher outboundMsgMatcher;
/**
* Create a new instance which will try to detect the types to decode and encode out of the type parameter
* of the class.
*/
protected MessageToMessageCodec() {
inboundMsgMatcher = TypeParameterMatcher.find(this, MessageToMessageCodec.class, "INBOUND_IN");
outboundMsgMatcher = TypeParameterMatcher.find(this, MessageToMessageCodec.class, "OUTBOUND_IN");
}
/**
* Create a new instance.
*
* @param inboundMessageType The type of messages to decode
* @param outboundMessageType The type of messages to encode
*/
protected MessageToMessageCodec(
Class<? extends INBOUND_IN> inboundMessageType, Class<? extends OUTBOUND_IN> outboundMessageType) {
inboundMsgMatcher = TypeParameterMatcher.get(inboundMessageType);
outboundMsgMatcher = TypeParameterMatcher.get(outboundMessageType);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
decoder.channelRead(ctx, msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
decoder.channelReadComplete(ctx);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
encoder.write(ctx, msg, promise);
}
/**
* Returns {@code true} if and only if the specified message can be decoded by this codec.
*
* @param msg the message
*/
public boolean acceptInboundMessage(Object msg) throws Exception {
return inboundMsgMatcher.match(msg);
}
/**
* Returns {@code true} if and only if the specified message can be encoded by this codec.
*
* @param msg the message
*/
public boolean acceptOutboundMessage(Object msg) throws Exception {
return outboundMsgMatcher.match(msg);
}
/**
* @see MessageToMessageEncoder#encode(ChannelHandlerContext, Object, List)
*/
protected abstract void encode(ChannelHandlerContext ctx, OUTBOUND_IN msg, List<Object> out)
throws Exception;
/**
* @see MessageToMessageDecoder#decode(ChannelHandlerContext, Object, List)
*/
protected abstract void decode(ChannelHandlerContext ctx, INBOUND_IN msg, List<Object> out)
throws Exception;
}
| MessageToMessageCodec |
java | apache__hadoop | hadoop-tools/hadoop-sls/src/main/java/org/apache/hadoop/yarn/sls/TaskContainerDefinition.java | {
"start": 1118,
"end": 1959
} | class ____ {
private long duration;
private Resource resource;
private int priority;
private String type;
private int count;
private ExecutionType executionType;
private long allocationId = -1;
private long requestDelay = 0;
private String hostname;
public long getDuration() {
return duration;
}
public Resource getResource() {
return resource;
}
public int getPriority() {
return priority;
}
public String getType() {
return type;
}
public int getCount() {
return count;
}
public ExecutionType getExecutionType() {
return executionType;
}
public long getAllocationId() {
return allocationId;
}
public long getRequestDelay() {
return requestDelay;
}
public String getHostname() {
return hostname;
}
public static final | TaskContainerDefinition |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringToDynamicIgnoreTest.java | {
"start": 1040,
"end": 1307
} | class ____ extends ToDynamicIgnoreTest {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/processor/SpringToDynamicIgnoreTest.xml");
}
}
| SpringToDynamicIgnoreTest |
java | square__moshi | examples/src/main/java/com/squareup/moshi/recipes/CustomAdapterWithDelegate.java | {
"start": 891,
"end": 1083
} | class ____ {
public void run() throws Exception {
// We want to match any Stage that starts with 'in-progress' as Stage.IN_PROGRESS
// and leave the rest of the | CustomAdapterWithDelegate |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/AnnotationIntrospector.java | {
"start": 35362,
"end": 39327
} | class ____
/**********************************************************************
*/
/**
* Method for accessing defined property serialization order (which may be
* partial). May return null if no ordering is defined.
*/
public String[] findSerializationPropertyOrder(MapperConfig<?> config, AnnotatedClass ac) {
return null;
}
/**
* Method for checking whether an annotation indicates that serialized properties
* for which no explicit is defined should be alphabetically (lexicograpically)
* ordered
*/
public Boolean findSerializationSortAlphabetically(MapperConfig<?> config, Annotated ann) {
return null;
}
/**
* Method for adding possible virtual properties to be serialized along
* with regular properties.
*/
public void findAndAddVirtualProperties(MapperConfig<?> config, AnnotatedClass ac,
List<BeanPropertyWriter> properties) { }
/*
/**********************************************************************
/* Serialization: property annotations
/**********************************************************************
*/
/**
* Method for checking whether given property accessors (method,
* field) has an annotation that suggests property name to use
* for serialization.
* Should return null if no annotation
* is found; otherwise a non-null name (possibly
* {@link PropertyName#USE_DEFAULT}, which means "use default heuristics").
*
* @param a Property accessor to check
*
* @return Name to use if found; null if not.
*/
public PropertyName findNameForSerialization(MapperConfig<?> config, Annotated a) {
return null;
}
/**
* Method for checking whether given method has an annotation
* that suggests the return value of annotated field or method
* should be used as "the key" of the object instance; usually
* serialized as a primitive value such as String or number.
*
* @return {@link Boolean#TRUE} if such annotation is found and is not disabled;
* {@link Boolean#FALSE} if disabled annotation (block) is found (to indicate
* accessor is definitely NOT to be used "as value"); or `null` if no
* information found.
*/
public Boolean hasAsKey(MapperConfig<?> config, Annotated a) {
return null;
}
/**
* Method for checking whether given method has an annotation
* that suggests that the return value of annotated method
* should be used as "the value" of the object instance; usually
* serialized as a primitive value such as String or number.
*
* @return {@link Boolean#TRUE} if such annotation is found and is not disabled;
* {@link Boolean#FALSE} if disabled annotation (block) is found (to indicate
* accessor is definitely NOT to be used "as value"); or `null` if no
* information found.
*/
public Boolean hasAsValue(MapperConfig<?> config, Annotated a) {
return null;
}
/**
* Method for checking whether given method has an annotation
* that suggests that the method is to serve as "any setter";
* method to be used for accessing set of miscellaneous "extra"
* properties, often bound with matching "any setter" method.
*
* @param ann Annotated entity to check
*
* @return True if such annotation is found (and is not disabled),
* false otherwise
*/
public Boolean hasAnyGetter(MapperConfig<?> config, Annotated ann) {
return null;
}
/**
* Finds the explicitly defined names, if any, of the given set of {@code Enum} values.
* The method overwrites entries in the incoming {@code names} array with the explicit
* names found, if any, leaving other entries unmodified.
*
* @param config the mapper configuration to use
* @param annotatedClass the annotated | annotations |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/cache/spi/support/AbstractDomainDataRegion.java | {
"start": 7066,
"end": 7974
} | interface ____ {
void destroy();
}
protected void releaseDataAccess(EntityDataAccess cacheAccess) {
if ( cacheAccess instanceof Destructible destructible ) {
destructible.destroy();
}
}
protected void releaseDataAccess(NaturalIdDataAccess cacheAccess) {
if ( cacheAccess instanceof Destructible destructible ) {
destructible.destroy();
}
}
protected void releaseDataAccess(CollectionDataAccess cacheAccess) {
if ( cacheAccess instanceof Destructible destructible ) {
destructible.destroy();
}
}
@Override
public void destroy() throws CacheException {
for ( var cacheAccess : entityDataAccessMap.values() ) {
releaseDataAccess( cacheAccess );
}
for ( var cacheAccess : naturalIdDataAccessMap.values() ) {
releaseDataAccess( cacheAccess );
}
for ( var cacheAccess : collectionDataAccessMap.values() ) {
releaseDataAccess( cacheAccess );
}
}
}
| Destructible |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-documentstore/src/main/java/org/apache/hadoop/yarn/server/timelineservice/documentstore/reader/cosmosdb/CosmosDBDocumentStoreReader.java | {
"start": 2212,
"end": 10189
} | class ____<TimelineDoc extends TimelineDocument>
implements DocumentStoreReader<TimelineDoc> {
private static final Logger LOG = LoggerFactory
.getLogger(CosmosDBDocumentStoreReader.class);
private static final int DEFAULT_DOCUMENTS_SIZE = 1;
private static AsyncDocumentClient client;
private final String databaseName;
private final static String COLLECTION_LINK = "/dbs/%s/colls/%s";
private final static String SELECT_TOP_FROM_COLLECTION = "SELECT TOP %d * " +
"FROM %s c";
private final static String SELECT_ALL_FROM_COLLECTION =
"SELECT * FROM %s c";
private final static String SELECT_DISTINCT_TYPES_FROM_COLLECTION =
"SELECT distinct c.type FROM %s c";
private static final String ENTITY_TYPE_COLUMN = "type";
private final static String WHERE_CLAUSE = " WHERE ";
private final static String AND_OPERATOR = " AND ";
private final static String CONTAINS_FUNC_FOR_ID = " CONTAINS(c.id, \"%s\") ";
private final static String CONTAINS_FUNC_FOR_TYPE = " CONTAINS(c.type, " +
"\"%s\") ";
private final static String ORDER_BY_CLAUSE = " ORDER BY c.createdTime";
// creating thread pool of size, half of the total available threads from JVM
private static ExecutorService executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors() / 2);
private static Scheduler schedulerForBlockingWork =
Schedulers.from(executorService);
public CosmosDBDocumentStoreReader(Configuration conf) {
LOG.info("Initializing Cosmos DB DocumentStoreReader...");
databaseName = DocumentStoreUtils.getCosmosDBDatabaseName(conf);
initCosmosDBClient(conf);
}
private synchronized void initCosmosDBClient(Configuration conf) {
// making CosmosDB Async Client Singleton
if (client == null) {
LOG.info("Creating Cosmos DB Reader Async Client...");
client = DocumentStoreUtils.createCosmosDBAsyncClient(conf);
addShutdownHook();
}
}
@Override
public List<TimelineDoc> readDocumentList(String collectionName,
TimelineReaderContext context, final Class<TimelineDoc> timelineDocClass,
long size) throws NoDocumentFoundException {
final List<TimelineDoc> result = queryDocuments(collectionName,
context, timelineDocClass, size);
if (result.size() > 0) {
return result;
}
throw new NoDocumentFoundException("No documents were found while " +
"querying Collection : " + collectionName);
}
@Override
public Set<String> fetchEntityTypes(String collectionName,
TimelineReaderContext context) {
StringBuilder queryStrBuilder = new StringBuilder();
queryStrBuilder.append(
String.format(SELECT_DISTINCT_TYPES_FROM_COLLECTION, collectionName));
String sqlQuery = addPredicates(context, collectionName, queryStrBuilder);
LOG.debug("Querying Collection : {} , with query {}", collectionName,
sqlQuery);
return Sets.newHashSet(client.queryDocuments(
String.format(COLLECTION_LINK, databaseName, collectionName),
sqlQuery, new FeedOptions())
.map(FeedResponse::getResults) // Map the page to the list of documents
.concatMap(Observable::from)
.map(document -> String.valueOf(document.get(ENTITY_TYPE_COLUMN)))
.toList()
.subscribeOn(schedulerForBlockingWork)
.toBlocking()
.single());
}
@Override
public TimelineDoc readDocument(String collectionName, TimelineReaderContext
context, final Class<TimelineDoc> timelineDocClass)
throws NoDocumentFoundException {
final List<TimelineDoc> result = queryDocuments(collectionName,
context, timelineDocClass, DEFAULT_DOCUMENTS_SIZE);
if(result.size() > 0) {
return result.get(0);
}
throw new NoDocumentFoundException("No documents were found while " +
"querying Collection : " + collectionName);
}
private List<TimelineDoc> queryDocuments(String collectionName,
TimelineReaderContext context, final Class<TimelineDoc> docClass,
final long maxDocumentsSize) {
final String sqlQuery = buildQueryWithPredicates(context, collectionName,
maxDocumentsSize);
LOG.debug("Querying Collection : {} , with query {}", collectionName,
sqlQuery);
return client.queryDocuments(String.format(COLLECTION_LINK,
databaseName, collectionName), sqlQuery, new FeedOptions())
.map(FeedResponse::getResults) // Map the page to the list of documents
.concatMap(Observable::from)
.map(document -> {
TimelineDoc resultDoc = document.toObject(docClass);
if (resultDoc.getCreatedTime() == 0 &&
document.getTimestamp() != null) {
resultDoc.setCreatedTime(document.getTimestamp().getTime());
}
return resultDoc;
})
.toList()
.subscribeOn(schedulerForBlockingWork)
.toBlocking()
.single();
}
private String buildQueryWithPredicates(TimelineReaderContext context,
String collectionName, long size) {
StringBuilder queryStrBuilder = new StringBuilder();
if (size == -1) {
queryStrBuilder.append(String.format(SELECT_ALL_FROM_COLLECTION,
collectionName));
} else {
queryStrBuilder.append(String.format(SELECT_TOP_FROM_COLLECTION, size,
collectionName));
}
return addPredicates(context, collectionName, queryStrBuilder);
}
@VisibleForTesting
String addPredicates(TimelineReaderContext context,
String collectionName, StringBuilder queryStrBuilder) {
boolean hasPredicate = false;
queryStrBuilder.append(WHERE_CLAUSE);
if (!DocumentStoreUtils.isNullOrEmpty(context.getClusterId())) {
hasPredicate = true;
queryStrBuilder.append(String.format(CONTAINS_FUNC_FOR_ID,
context.getClusterId()));
}
if (!DocumentStoreUtils.isNullOrEmpty(context.getUserId())) {
hasPredicate = true;
queryStrBuilder.append(AND_OPERATOR)
.append(String.format(CONTAINS_FUNC_FOR_ID, context.getUserId()));
}
if (!DocumentStoreUtils.isNullOrEmpty(context.getFlowName())) {
hasPredicate = true;
queryStrBuilder.append(AND_OPERATOR)
.append(String.format(CONTAINS_FUNC_FOR_ID, context.getFlowName()));
}
if (!DocumentStoreUtils.isNullOrEmpty(context.getAppId())) {
hasPredicate = true;
queryStrBuilder.append(AND_OPERATOR)
.append(String.format(CONTAINS_FUNC_FOR_ID, context.getAppId()));
}
if (!DocumentStoreUtils.isNullOrEmpty(context.getEntityId())) {
hasPredicate = true;
queryStrBuilder.append(AND_OPERATOR)
.append(String.format(CONTAINS_FUNC_FOR_ID, context.getEntityId()));
}
if (context.getFlowRunId() != null) {
hasPredicate = true;
queryStrBuilder.append(AND_OPERATOR)
.append(String.format(CONTAINS_FUNC_FOR_ID, context.getFlowRunId()));
}
if (!DocumentStoreUtils.isNullOrEmpty(context.getEntityType())){
hasPredicate = true;
queryStrBuilder.append(AND_OPERATOR)
.append(String.format(CONTAINS_FUNC_FOR_TYPE,
context.getEntityType()));
}
if (hasPredicate) {
queryStrBuilder.append(ORDER_BY_CLAUSE);
LOG.debug("CosmosDB Sql Query with predicates : {}", queryStrBuilder);
return queryStrBuilder.toString();
}
throw new IllegalArgumentException("The TimelineReaderContext does not " +
"have enough information to query documents for Collection : " +
collectionName);
}
@Override
public synchronized void close() {
if (client != null) {
LOG.info("Closing Cosmos DB Reader Async Client...");
client.close();
client = null;
}
}
private void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new SubjectInheritingThread(() -> {
if (executorService != null) {
executorService.shutdown();
}
}));
}
}
| CosmosDBDocumentStoreReader |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/SoftAssertions_combined_with_asInstanceOf_Test.java | {
"start": 9253,
"end": 16191
} | class ____ extends BaseAssertionsTest {
private SoftAssertions softly;
@BeforeEach
void setup() {
Assertions.setRemoveAssertJRelatedElementsFromStackTrace(false);
softly = new SoftAssertions();
}
@Test
void soft_assertions_should_work() {
// GIVEN
Object value = "abc";
// WHEN
softly.assertThat(value)
.as("startsWith")
.asInstanceOf(STRING)
.startsWith("b");
// THEN
List<Throwable> errorsCollected = softly.errorsCollected();
assertThat(errorsCollected).hasSize(1);
assertThat(errorsCollected.get(0)).hasMessageContaining("[startsWith]");
}
@ParameterizedTest(name = "with {1}")
@MethodSource("should_work_with_any_InstanceOfFactory_source")
void should_work_with_any_InstanceOfFactory(Object actual, InstanceOfAssertFactory<?, ?> instanceOfAssertFactory) {
softly.assertThat(actual).asInstanceOf(instanceOfAssertFactory);
}
public static Stream<Arguments> should_work_with_any_InstanceOfFactory_source() throws MalformedURLException {
Future<String> future = completedFuture("foo");
CompletionStage<String> completionStage = completedFuture("foo");
CharSequence charSequence = new StringBuilder();
return Stream.of(arguments(new Object[0], ARRAY),
arguments(new AtomicBoolean(true), ATOMIC_BOOLEAN),
arguments(new AtomicInteger(1), ATOMIC_INTEGER),
arguments(new AtomicIntegerArray(5), ATOMIC_INTEGER_ARRAY),
arguments(AtomicIntegerFieldUpdater.newUpdater(Data.class, "intField"), ATOMIC_INTEGER_FIELD_UPDATER),
arguments(new AtomicLong(5L), ATOMIC_LONG),
arguments(new AtomicLongArray(5), ATOMIC_LONG_ARRAY),
arguments(AtomicLongFieldUpdater.newUpdater(Data.class, "longField"), ATOMIC_LONG_FIELD_UPDATER),
arguments(new AtomicMarkableReference<>("", false), ATOMIC_MARKABLE_REFERENCE),
arguments(new AtomicReference<>("abc"), ATOMIC_REFERENCE),
arguments(new AtomicReferenceArray<>(3), ATOMIC_REFERENCE_ARRAY),
arguments(newUpdater(Data.class, String.class, "stringField"), ATOMIC_REFERENCE_FIELD_UPDATER),
arguments(new AtomicStampedReference<>(0, 0), ATOMIC_STAMPED_REFERENCE),
arguments(BigDecimal.ONE, BIG_DECIMAL),
arguments(BigInteger.ONE, BIG_INTEGER),
arguments(true, BOOLEAN),
arguments(new boolean[0], BOOLEAN_ARRAY),
arguments(new boolean[0][0], BOOLEAN_2D_ARRAY),
arguments((byte) 1, BYTE),
arguments(Byte.valueOf("1"), BYTE),
arguments(new byte[0], BYTE_ARRAY),
arguments(new byte[0][0], BYTE_2D_ARRAY),
arguments(new char[0], CHAR_ARRAY),
arguments(new char[0][0], CHAR_2D_ARRAY),
arguments(charSequence, CHAR_SEQUENCE),
arguments('a', CHARACTER),
arguments(Character.valueOf('a'), CHARACTER),
arguments(TolkienCharacter.class, CLASS),
arguments(list("foo"), COLLECTION),
arguments(completedFuture("foo"), COMPLETABLE_FUTURE),
arguments(completionStage, COMPLETION_STAGE),
arguments(new Date(), DATE),
arguments(0d, DOUBLE),
arguments(Double.valueOf(0d), DOUBLE),
arguments(new double[0], DOUBLE_ARRAY),
arguments(new double[0][0], DOUBLE_2D_ARRAY),
arguments((DoublePredicate) d -> d == 0.0, DOUBLE_PREDICATE),
arguments(DoubleStream.empty(), DOUBLE_STREAM),
arguments(Duration.ZERO, DURATION),
arguments(Period.ZERO, PERIOD),
arguments(new File("foo"), FILE),
arguments(Float.valueOf("0.0"), FLOAT),
arguments(new float[0], FLOAT_ARRAY),
arguments(new float[0][0], FLOAT_2D_ARRAY),
arguments(future, FUTURE),
arguments(new ByteArrayInputStream("stream".getBytes()), INPUT_STREAM),
arguments(Instant.now(), INSTANT),
arguments(new int[0], INT_ARRAY),
arguments(new int[0][0], INT_2D_ARRAY),
arguments((IntPredicate) i -> i == 0, INT_PREDICATE),
arguments(IntStream.empty(), INT_STREAM),
arguments(1, INTEGER),
arguments(newHashSet(), ITERABLE),
arguments(list("foo").iterator(), ITERATOR),
arguments(list("foo"), LIST),
arguments(LocalDate.now(), LOCAL_DATE),
arguments(LocalDateTime.now(), LOCAL_DATE_TIME),
arguments(5L, LONG),
arguments(new LongAdder(), LONG_ADDER),
arguments(new long[0], LONG_ARRAY),
arguments(new long[0][0], LONG_2D_ARRAY),
arguments((LongPredicate) l -> l == 0, LONG_PREDICATE),
arguments(LongStream.empty(), LONG_STREAM),
arguments(newHashMap("k", "v"), MAP),
arguments(Pattern.compile("a*").matcher("aaa"), MATCHER),
arguments(OffsetDateTime.now(), OFFSET_DATE_TIME),
arguments(OffsetTime.now(), OFFSET_TIME),
arguments(Optional.empty(), OPTIONAL),
arguments(OptionalDouble.empty(), OPTIONAL_DOUBLE),
arguments(OptionalInt.empty(), OPTIONAL_INT),
arguments(OptionalLong.empty(), OPTIONAL_LONG),
arguments(Path.of("."), PATH),
arguments((Predicate<String>) String::isEmpty, PREDICATE),
arguments(set("foo"), SET),
arguments(Short.MIN_VALUE, SHORT),
arguments(new short[0], SHORT_ARRAY),
arguments(new short[0][0], SHORT_2D_ARRAY),
arguments(Stream.empty(), STREAM),
arguments("foo", STRING),
arguments(new StringBuffer(), STRING_BUFFER),
arguments(new StringBuilder(), STRING_BUILDER),
arguments(new Exception(), THROWABLE),
arguments(URI.create("http://localhost"), URI_TYPE),
arguments(URI.create("http://localhost").toURL(), URL_TYPE),
arguments(ZonedDateTime.now(), ZONED_DATE_TIME),
arguments(ZonedDateTime.now(), TEMPORAL));
}
static | SoftAssertions_combined_with_asInstanceOf_Test |
java | apache__hadoop | hadoop-tools/hadoop-sls/src/main/java/org/apache/hadoop/yarn/sls/scheduler/SchedulerMetrics.java | {
"start": 22553,
"end": 25226
} | enum ____ {
PENDING_MEMORY("pending.memory"),
PENDING_VCORES("pending.cores"),
ALLOCATED_MEMORY("allocated.memory"),
ALLOCATED_VCORES("allocated.cores");
private String value;
QueueMetric(String value) {
this.value = value;
}
}
private String getQueueMetricName(String queue, QueueMetric metric) {
return "counter.queue." + queue + "." + metric.value;
}
void updateQueueMetrics(Resource pendingResource, Resource allocatedResource,
String queueName) {
trackQueue(queueName);
SortedMap<String, Counter> counterMap = metrics.getCounters();
for(QueueMetric metric : QueueMetric.values()) {
String metricName = getQueueMetricName(queueName, metric);
if (metric == QueueMetric.PENDING_MEMORY) {
counterMap.get(metricName).inc(pendingResource.getMemorySize());
} else if (metric == QueueMetric.PENDING_VCORES) {
counterMap.get(metricName).inc(pendingResource.getVirtualCores());
} else if (metric == QueueMetric.ALLOCATED_MEMORY) {
counterMap.get(metricName).inc(allocatedResource.getMemorySize());
} else if (metric == QueueMetric.ALLOCATED_VCORES){
counterMap.get(metricName).inc(allocatedResource.getVirtualCores());
}
}
}
void updateQueueMetricsByRelease(Resource releaseResource, String queue) {
SortedMap<String, Counter> counterMap = metrics.getCounters();
String name = getQueueMetricName(queue, QueueMetric.ALLOCATED_MEMORY);
if (!counterMap.containsKey(name)) {
metrics.counter(name);
counterMap = metrics.getCounters();
}
counterMap.get(name).inc(-releaseResource.getMemorySize());
String vcoreMetric =
getQueueMetricName(queue, QueueMetric.ALLOCATED_VCORES);
if (!counterMap.containsKey(vcoreMetric)) {
metrics.counter(vcoreMetric);
counterMap = metrics.getCounters();
}
counterMap.get(vcoreMetric).inc(-releaseResource.getVirtualCores());
}
public void addTrackedApp(ApplicationId appId,
String oldAppId) {
trackApp(appId, oldAppId);
}
public void removeTrackedApp(String oldAppId) {
untrackApp(oldAppId);
}
public void addAMRuntime(ApplicationId appId, long traceStartTimeMS,
long traceEndTimeMS, long simulateStartTimeMS, long simulateEndTimeMS) {
try {
// write job runtime information
String runtimeInfo = appId + "," + traceStartTimeMS + "," +
traceEndTimeMS + "," + simulateStartTimeMS +
"," + simulateEndTimeMS;
jobRuntimeLogBW.write(runtimeInfo + EOL);
jobRuntimeLogBW.flush();
} catch (IOException e) {
LOG.info(e.getMessage());
}
}
}
| QueueMetric |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8648ProjectEventsTest.java | {
"start": 903,
"end": 3310
} | class ____ extends AbstractMavenIntegrationTestCase {
@Test
public void test() throws Exception {
File extensionDir = extractResources("/mng-8648/extension");
Verifier verifier = newVerifier(extensionDir.getAbsolutePath());
verifier.addCliArgument("install");
verifier.execute();
verifier.verifyErrorFreeLog();
File projectDir = extractResources("/mng-8648/project");
verifier = newVerifier(projectDir.getAbsolutePath());
verifier.addCliArguments("compile", "-b", "concurrent", "-T5");
try {
verifier.execute();
} catch (VerificationException expected) {
}
// The root project is marked as successful with the traditional builder
// With the concurrent builder, it gets no finish event and in the reactor summary it is listed as "skipped"
verifier.verifyTextInLog("org.apache.maven.its.mng8648:root:pom:1-SNAPSHOT ProjectStarted");
verifier.verifyTextInLog("org.apache.maven.its.mng8648:root:pom:1-SNAPSHOT ProjectSucceeded");
verifier.verifyTextInLog("org.apache.maven.its.mng8648:subproject-a:jar:1-SNAPSHOT ProjectStarted");
verifier.verifyTextInLog("org.apache.maven.its.mng8648:subproject-a:jar:1-SNAPSHOT ProjectSucceeded");
verifier.verifyTextInLog("org.apache.maven.its.mng8648:subproject-b:jar:1-SNAPSHOT ProjectStarted");
verifier.verifyTextInLog("org.apache.maven.its.mng8648:subproject-b:jar:1-SNAPSHOT ProjectSucceeded");
verifier.verifyTextInLog("org.apache.maven.its.mng8648:subproject-c:jar:1-SNAPSHOT ProjectStarted");
verifier.verifyTextInLog("org.apache.maven.its.mng8648:subproject-c:jar:1-SNAPSHOT ProjectFailed");
// With the traditional builder, project D is not reported at all (it is never even started),
// and in the reactor summary it is listed as "skipped".
// With the concurrent builder, it should be started and later reported as "skipped"
verifier.verifyTextInLog("org.apache.maven.its.mng8648:subproject-d:jar:1-SNAPSHOT ProjectStarted");
verifier.verifyTextInLog("org.apache.maven.its.mng8648:subproject-d:jar:1-SNAPSHOT ProjectSkipped");
// Make sure there's no problem with the event spy
verifier.verifyTextNotInLog("Failed to notify spy org.apache.maven.its.mng8648.ProjectEventSpy");
}
}
| MavenITmng8648ProjectEventsTest |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportOpenJobAction.java | {
"start": 18778,
"end": 21051
} | class ____ only be used when opening a job
OpenJobAction.JobParams params = (OpenJobAction.JobParams) persistentTask.getParams();
Optional<ElasticsearchException> assignmentException = checkAssignmentState(assignment, params.getJobId(), logger);
if (assignmentException.isPresent()) {
exception = assignmentException.get();
// The persistent task should be cancelled so that the observed outcome is the
// same as if the "fast fail" validation on the coordinating node had failed
shouldCancel = true;
return true;
}
}
switch (jobState) {
// The OPENING case here is expected to be incredibly short-lived, just occurring during the
// time period when a job has successfully been assigned to a node but the request to update
// its task state is still in-flight. (The long-lived OPENING case when a lazy node needs to
// be added to the cluster to accommodate the job was dealt with higher up this method when the
// magic AWAITING_LAZY_ASSIGNMENT assignment was checked for.)
case OPENING:
case CLOSED:
return false;
case OPENED:
node = persistentTask.getExecutorNode();
return true;
case CLOSING:
exception = ExceptionsHelper.conflictStatusException(
"The job has been {} while waiting to be {}",
JobState.CLOSED,
JobState.OPENED
);
return true;
case FAILED:
default:
// Default http status is SERVER ERROR
exception = ExceptionsHelper.serverError(
"Unexpected job state [{}] {}while waiting for job to be {}",
jobState,
reason == null ? "" : "with reason [" + reason + "] ",
JobState.OPENED
);
return true;
}
}
}
}
| must |
java | apache__camel | components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/queue/HazelcastQueueConsumerMode.java | {
"start": 863,
"end": 1778
} | enum ____ {
LISTEN("listen"),
POLL("poll");
private static final HazelcastQueueConsumerMode[] VALUES = values();
private final String mode;
HazelcastQueueConsumerMode(String mode) {
this.mode = mode;
}
public static HazelcastQueueConsumerMode getHazelcastOperation(String name) {
if (name == null) {
return null;
}
for (HazelcastQueueConsumerMode hazelcastQueueConsumerMode : VALUES) {
if (hazelcastQueueConsumerMode.toString().equalsIgnoreCase(name)
|| hazelcastQueueConsumerMode.name().equalsIgnoreCase(name)) {
return hazelcastQueueConsumerMode;
}
}
throw new IllegalArgumentException(String.format("Mode '%s' is not supported by this component.", name));
}
@Override
public String toString() {
return mode;
}
}
| HazelcastQueueConsumerMode |
java | apache__camel | components/camel-amqp/src/test/java/org/apache/camel/component/amqp/AMQPConfigTest.java | {
"start": 1549,
"end": 9003
} | class ____ {
@RegisterExtension
protected static CamelContextExtension contextExtension = new DefaultCamelContextExtension();
@Test
public void testComponent() {
AMQPComponent component = contextExtension.getContext().getComponent("amqp", AMQPComponent.class);
assertTrue(component.getConnectionFactory() instanceof JmsConnectionFactory);
JmsConnectionFactory connectionFactory = (JmsConnectionFactory) component.getConnectionFactory();
assertNull(connectionFactory.getUsername());
assertNull(connectionFactory.getPassword());
assertEquals("amqp://remotehost:5556", connectionFactory.getRemoteURI());
assertEquals("topic://", connectionFactory.getTopicPrefix());
}
@Test
public void testConfiguredComponent() {
AMQPComponent customizedComponent = contextExtension.getContext().getComponent("amqp-configured", AMQPComponent.class);
assertEquals("remotehost", customizedComponent.getHost());
assertEquals(5556, customizedComponent.getPort());
assertEquals("camel", customizedComponent.getUsername());
assertEquals("rider", customizedComponent.getPassword());
assertTrue(customizedComponent.getConnectionFactory() instanceof JmsConnectionFactory);
JmsConnectionFactory connectionFactory = (JmsConnectionFactory) customizedComponent.getConnectionFactory();
assertEquals("camel", connectionFactory.getUsername());
assertEquals("rider", connectionFactory.getPassword());
assertEquals("amqp://remotehost:5556", connectionFactory.getRemoteURI());
assertEquals("topic://", connectionFactory.getTopicPrefix());
}
@Test
public void testConfiguredSslComponent() {
AMQPComponent customizedComponent = contextExtension.getContext().getComponent("amqps-configured", AMQPComponent.class);
assertTrue(customizedComponent.getUseSsl());
assertEquals("server-ca-truststore.p12", customizedComponent.getTrustStoreLocation());
assertEquals("securepass", customizedComponent.getTrustStorePassword());
assertEquals("PKCS12", customizedComponent.getTrustStoreType());
assertEquals("server-keystore.p12", customizedComponent.getKeyStoreLocation());
assertEquals("securepass", customizedComponent.getKeyStorePassword());
assertEquals("PKCS12", customizedComponent.getKeyStoreType());
assertTrue(customizedComponent.getConnectionFactory() instanceof JmsConnectionFactory);
JmsConnectionFactory connectionFactory = (JmsConnectionFactory) customizedComponent.getConnectionFactory();
assertNull(connectionFactory.getUsername());
assertNull(connectionFactory.getPassword());
assertEquals(
"amqps://localhost:5672?transport.trustStoreLocation=server-ca-truststore.p12&transport.trustStoreType=PKCS12&transport.trustStorePassword=securepass&transport.keyStoreLocation=server-keystore.p12&transport.keyStoreType=PKCS12&transport.keyStorePassword=securepass",
connectionFactory.getRemoteURI());
assertEquals("topic://", connectionFactory.getTopicPrefix());
}
@Test
public void testEnabledSslComponent() {
AMQPComponent amqpSslEnabledComponent
= contextExtension.getContext().getComponent("amqps-enabled", AMQPComponent.class);
assertTrue(amqpSslEnabledComponent.getUseSsl());
assertNull(amqpSslEnabledComponent.getTrustStoreLocation());
assertNull(amqpSslEnabledComponent.getTrustStorePassword());
assertEquals("JKS", amqpSslEnabledComponent.getTrustStoreType());
assertNull(amqpSslEnabledComponent.getKeyStoreLocation());
assertNull(amqpSslEnabledComponent.getKeyStorePassword());
assertEquals("JKS", amqpSslEnabledComponent.getKeyStoreType());
assertTrue(amqpSslEnabledComponent.getConnectionFactory() instanceof JmsConnectionFactory);
JmsConnectionFactory connectionFactory = (JmsConnectionFactory) amqpSslEnabledComponent.getConnectionFactory();
assertNull(connectionFactory.getUsername());
assertNull(connectionFactory.getPassword());
assertEquals(
"amqps://localhost:5672?transport.trustStoreLocation=&transport.trustStoreType=JKS&transport.trustStorePassword=&transport.keyStoreLocation=&transport.keyStoreType=JKS&transport.keyStorePassword=",
connectionFactory.getRemoteURI());
assertEquals("topic://", connectionFactory.getTopicPrefix());
}
@Test
public void testComponentPort() {
AMQPComponent amqpComponent = contextExtension.getContext().getComponent("amqp-portonly", AMQPComponent.class);
assertEquals(5556, amqpComponent.getPort());
assertTrue(amqpComponent.getConnectionFactory() instanceof JmsConnectionFactory);
JmsConnectionFactory connectionFactory = (JmsConnectionFactory) amqpComponent.getConnectionFactory();
assertNull(connectionFactory.getUsername());
assertNull(connectionFactory.getPassword());
assertEquals("amqp://localhost:5556", connectionFactory.getRemoteURI());
assertEquals("topic://", connectionFactory.getTopicPrefix());
}
@Test
public void testNoTopicPrefix() {
AMQPComponent component = contextExtension.getContext().getComponent("amqp-notopicprefix", AMQPComponent.class);
assertFalse(component.getUseTopicPrefix());
assertTrue(component.getConnectionFactory() instanceof JmsConnectionFactory);
JmsConnectionFactory connectionFactory = (JmsConnectionFactory) component.getConnectionFactory();
assertNull(connectionFactory.getUsername());
assertNull(connectionFactory.getPassword());
assertEquals("amqp://localhost:5672", connectionFactory.getRemoteURI());
assertNull(connectionFactory.getTopicPrefix());
}
@ContextFixture
public void configureContext(CamelContext context) {
context.addComponent("amqp", amqpComponent("amqp://remotehost:5556"));
AMQPComponent amqpComponent = new AMQPComponent();
amqpComponent.setHost("remotehost");
amqpComponent.setPort(5556);
amqpComponent.setUsername("camel");
amqpComponent.setPassword("rider");
context.addComponent("amqp-configured", amqpComponent);
AMQPComponent amqpSslComponent = new AMQPComponent();
amqpSslComponent.setUseSsl(true);
amqpSslComponent.setTrustStoreLocation("server-ca-truststore.p12");
amqpSslComponent.setTrustStorePassword("securepass");
amqpSslComponent.setTrustStoreType("PKCS12");
amqpSslComponent.setKeyStoreLocation("server-keystore.p12");
amqpSslComponent.setKeyStorePassword("securepass");
amqpSslComponent.setKeyStoreType("PKCS12");
context.addComponent("amqps-configured", amqpSslComponent);
AMQPComponent amqpSslEnabledComponent = new AMQPComponent();
amqpSslEnabledComponent.setUseSsl(true);
context.addComponent("amqps-enabled", amqpSslEnabledComponent);
AMQPComponent amqpPortOnlyComponent = new AMQPComponent();
amqpPortOnlyComponent.setPort(5556);
context.addComponent("amqp-portonly", amqpPortOnlyComponent);
AMQPComponent amqpNoTopicPrefix = new AMQPComponent();
amqpNoTopicPrefix.setUseTopicPrefix(false);
context.addComponent("amqp-notopicprefix", amqpNoTopicPrefix);
}
}
| AMQPConfigTest |
java | spring-projects__spring-framework | spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceManagedTypesBeanRegistrationAotProcessorTests.java | {
"start": 8997,
"end": 9211
} | class ____ extends AbstractEntityManagerWithPackagesToScanConfiguration {
@Override
protected String packageToScan() {
return "org.springframework.orm.jpa.domain";
}
}
public static | JpaDomainConfiguration |
java | spring-projects__spring-boot | module/spring-boot-graphql-test/src/test/java/org/springframework/boot/graphql/test/autoconfigure/BookController.java | {
"start": 1016,
"end": 1166
} | class ____ {
@QueryMapping
public Book bookById(@Argument String id) {
return new Book("42", "Sample Book", 100, "Jane Spring");
}
}
| BookController |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/apidiff/Java8ApiCheckerTest.java | {
"start": 2904,
"end": 3124
} | class ____ {
void f(CRC32 c, byte[] b) {
c.update(b);
}
}
""")
.setArgs("-XepOpt:Java8ApiChecker:checkChecksum=false")
.doTest();
}
}
| Test |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/BucketsAggregator.java | {
"start": 2079,
"end": 12922
} | class ____ extends AggregatorBase {
private LongArray docCounts;
protected final DocCountProvider docCountProvider;
@SuppressWarnings("this-escape")
public BucketsAggregator(
String name,
AggregatorFactories factories,
AggregationContext aggCtx,
Aggregator parent,
CardinalityUpperBound bucketCardinality,
Map<String, Object> metadata
) throws IOException {
super(name, factories, aggCtx, parent, bucketCardinality, metadata);
docCounts = bigArrays().newLongArray(1, true);
docCountProvider = new DocCountProvider();
}
/**
* Ensure there are at least <code>maxBucketOrd</code> buckets available.
*/
public final void grow(long maxBucketOrd) {
docCounts = bigArrays().grow(docCounts, maxBucketOrd);
}
/**
* Utility method to collect the given doc in the given bucket (identified by the bucket ordinal)
*/
public final void collectBucket(LeafBucketCollector subCollector, int doc, long bucketOrd) throws IOException {
grow(bucketOrd + 1);
int docCount = docCountProvider.getDocCount(doc);
if (docCounts.increment(bucketOrd, docCount) == docCount) {
checkRealMemoryCB("allocated_buckets");
}
subCollector.collect(doc, bucketOrd);
}
/**
* Same as {@link #collectBucket(LeafBucketCollector, int, long)}, but doesn't check if the docCounts needs to be re-sized.
*/
public final void collectExistingBucket(LeafBucketCollector subCollector, int doc, long bucketOrd) throws IOException {
docCounts.increment(bucketOrd, docCountProvider.getDocCount(doc));
subCollector.collect(doc, bucketOrd);
}
/**
* Merge doc counts. If the {@linkplain Aggregator} is delayed then you must also call
* {@link BestBucketsDeferringCollector#rewriteBuckets(LongUnaryOperator)} to merge the delayed buckets.
* @param mergeMap a unary operator which maps a bucket's ordinal to the ordinal it should be merged with.
* If a bucket's ordinal is mapped to -1 then the bucket is removed entirely.
*/
public final void rewriteBuckets(long newNumBuckets, LongUnaryOperator mergeMap) {
LongArray oldDocCounts = docCounts;
boolean success = false;
try {
docCounts = bigArrays().newLongArray(newNumBuckets, true);
success = true;
for (long i = 0; i < oldDocCounts.size(); i++) {
long docCount = oldDocCounts.get(i);
if (docCount == 0) continue;
// Skip any in the map which have been "removed", signified with -1
long destinationOrdinal = mergeMap.applyAsLong(i);
if (destinationOrdinal != -1) {
docCounts.increment(destinationOrdinal, docCount);
}
}
} finally {
if (success) {
oldDocCounts.close();
}
}
}
public LongArray getDocCounts() {
return docCounts;
}
/**
* Utility method to increment the doc counts of the given bucket (identified by the bucket ordinal)
*/
public final void incrementBucketDocCount(long bucketOrd, long inc) {
docCounts = bigArrays().grow(docCounts, bucketOrd + 1);
docCounts.increment(bucketOrd, inc);
}
/**
* Utility method to return the number of documents that fell in the given bucket (identified by the bucket ordinal)
*/
public final long bucketDocCount(long bucketOrd) {
if (bucketOrd >= docCounts.size()) {
// This may happen eg. if no document in the highest buckets is accepted by a sub aggregator.
// For example, if there is a long terms agg on 3 terms 1,2,3 with a sub filter aggregator and if no document with 3 as a value
// matches the filter, then the filter will never collect bucket ord 3. However, the long terms agg will call
// bucketAggregations(3) on the filter aggregator anyway to build sub-aggregations.
return 0;
} else {
return docCounts.get(bucketOrd);
}
}
/**
* Hook to allow taking an action before building the sub agg results.
*/
protected void prepareSubAggs(LongArray ordsToCollect) throws IOException {}
/**
* Build the results of the sub-aggregations of the buckets at each of
* the provided ordinals.
* <p>
* Most aggregations should probably use something like
* {@link #buildSubAggsForAllBuckets(ObjectArray, LongArray, BiConsumer)}
* or {@link #buildSubAggsForAllBuckets(ObjectArray, ToLongFunction, BiConsumer)}
* or {@link #buildAggregationsForVariableBuckets(LongArray, LongKeyedBucketOrds, BucketBuilderForVariable, ResultBuilderForVariable)}
* or {@link #buildAggregationsForFixedBucketCount(LongArray, int, BucketBuilderForFixedCount, Function)}
* or {@link #buildAggregationsForSingleBucket(LongArray, SingleBucketResultBuilder)}
* instead of calling this directly.
* @return the sub-aggregation results in the same order as the provided
* array of ordinals
*/
protected final IntFunction<InternalAggregations> buildSubAggsForBuckets(LongArray bucketOrdsToCollect) throws IOException {
if (context.isCancelled()) {
throw new TaskCancelledException("not building sub-aggregations due to task cancellation");
}
prepareSubAggs(bucketOrdsToCollect);
InternalAggregation[][] aggregations = new InternalAggregation[subAggregators.length][];
for (int i = 0; i < subAggregators.length; i++) {
checkRealMemoryCB("building_sub_aggregation");
aggregations[i] = subAggregators[i].buildAggregations(bucketOrdsToCollect);
}
return subAggsForBucketFunction(aggregations);
}
private static IntFunction<InternalAggregations> subAggsForBucketFunction(InternalAggregation[][] aggregations) {
return ord -> InternalAggregations.from(new AbstractList<>() {
@Override
public InternalAggregation get(int index) {
return aggregations[index][ord];
}
@Override
public int size() {
return aggregations.length;
}
});
}
/**
* Similarly to {@link #buildSubAggsForAllBuckets(ObjectArray, LongArray, BiConsumer)}
* but it needs to build the bucket ordinals. This method usually requires for buckets
* to contain the bucket ordinal.
* @param buckets the buckets to finish building
* @param bucketToOrd how to convert a bucket into an ordinal
* @param setAggs how to set the sub-aggregation results on a bucket
*/
protected final <B> void buildSubAggsForAllBuckets(
ObjectArray<B[]> buckets,
ToLongFunction<B> bucketToOrd,
BiConsumer<B, InternalAggregations> setAggs
) throws IOException {
long totalBucketOrdsToCollect = 0;
for (long b = 0; b < buckets.size(); b++) {
totalBucketOrdsToCollect += buckets.get(b).length;
}
try (LongArray bucketOrdsToCollect = bigArrays().newLongArray(totalBucketOrdsToCollect)) {
int s = 0;
for (long ord = 0; ord < buckets.size(); ord++) {
for (B bucket : buckets.get(ord)) {
bucketOrdsToCollect.set(s++, bucketToOrd.applyAsLong(bucket));
}
}
buildSubAggsForAllBuckets(buckets, bucketOrdsToCollect, setAggs);
}
}
/**
* Build the sub aggregation results for a list of buckets and set them on
* the buckets. This is usually used by aggregations that are selective
* in which bucket they build. They use some mechanism of selecting a list
* of buckets to build use this method to "finish" building the results.
* @param buckets the buckets to finish building
* @param bucketOrdsToCollect bucket ordinals
* @param setAggs how to set the sub-aggregation results on a bucket
*/
protected final <B> void buildSubAggsForAllBuckets(
ObjectArray<B[]> buckets,
LongArray bucketOrdsToCollect,
BiConsumer<B, InternalAggregations> setAggs
) throws IOException {
var results = buildSubAggsForBuckets(bucketOrdsToCollect);
int s = 0;
for (long ord = 0; ord < buckets.size(); ord++) {
for (B value : buckets.get(ord)) {
setAggs.accept(value, results.apply(s++));
}
}
}
/**
* Build aggregation results for an aggregator that has a fixed number of buckets per owning ordinal.
* @param <B> the type of the bucket
* @param owningBucketOrds owning bucket ordinals for which to build the results
* @param bucketsPerOwningBucketOrd how many buckets there are per ord
* @param bucketBuilder how to build a bucket
* @param resultBuilder how to build a result from buckets
*/
protected final <B> InternalAggregation[] buildAggregationsForFixedBucketCount(
LongArray owningBucketOrds,
int bucketsPerOwningBucketOrd,
BucketBuilderForFixedCount<B> bucketBuilder,
Function<List<B>, InternalAggregation> resultBuilder
) throws IOException {
try (LongArray bucketOrdsToCollect = bigArrays().newLongArray(owningBucketOrds.size() * bucketsPerOwningBucketOrd)) {
final int[] bucketOrdIdx = new int[] { 0 };
for (long i = 0; i < owningBucketOrds.size(); i++) {
long ord = owningBucketOrds.get(i) * bucketsPerOwningBucketOrd;
for (int offsetInOwningOrd = 0; offsetInOwningOrd < bucketsPerOwningBucketOrd; offsetInOwningOrd++) {
bucketOrdsToCollect.set(bucketOrdIdx[0]++, ord++);
}
}
bucketOrdIdx[0] = 0;
var subAggregationResults = buildSubAggsForBuckets(bucketOrdsToCollect);
return buildAggregations(Math.toIntExact(owningBucketOrds.size()), ordIdx -> {
List<B> buckets = new ArrayList<>(bucketsPerOwningBucketOrd);
for (int offsetInOwningOrd = 0; offsetInOwningOrd < bucketsPerOwningBucketOrd; offsetInOwningOrd++) {
checkRealMemoryCBForInternalBucket();
buckets.add(
bucketBuilder.build(
offsetInOwningOrd,
bucketDocCount(bucketOrdsToCollect.get(bucketOrdIdx[0])),
subAggregationResults.apply(bucketOrdIdx[0]++)
)
);
}
return resultBuilder.apply(buckets);
});
}
}
@FunctionalInterface
protected | BucketsAggregator |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/settings/Settings.java | {
"start": 37693,
"end": 40509
} | class ____ {
// we use a sorted map for consistent serialization when using getAsMap()
private final Map<String, Object> map = new TreeMap<>();
private final SetOnce<SecureSettings> secureSettings = new SetOnce<>();
private Builder() {
}
public Set<String> keys() {
return this.map.keySet();
}
/**
* Removes the provided setting from the internal map holding the current list of settings.
*/
public String remove(String key) {
return Settings.toString(map.remove(key));
}
/**
* Returns a setting value based on the setting key.
*/
public String get(String key) {
return Settings.toString(map.get(key));
}
/** Return the current secure settings, or {@code null} if none have been set. */
public SecureSettings getSecureSettings() {
return secureSettings.get();
}
public Builder setSecureSettings(SecureSettings secureSettings) {
if (secureSettings.isLoaded() == false) {
throw new IllegalStateException("Secure settings must already be loaded");
}
if (this.secureSettings.get() != null) {
throw new IllegalArgumentException(
"Secure settings already set. Existing settings: "
+ this.secureSettings.get().getSettingNames()
+ ", new settings: "
+ secureSettings.getSettingNames()
);
}
this.secureSettings.set(secureSettings);
return this;
}
/**
* Sets a path setting with the provided setting key and path.
*
* @param key The setting key
* @param path The setting path
* @return The builder
*/
public Builder put(String key, Path path) {
return put(key, path.toString());
}
/**
* Sets a time value setting with the provided setting key and value.
*
* @param key The setting key
* @param timeValue The setting timeValue
* @return The builder
*/
public Builder put(final String key, final TimeValue timeValue) {
return put(key, timeValue.getStringRep());
}
/**
* Sets a byteSizeValue setting with the provided setting key and byteSizeValue.
*
* @param key The setting key
* @param byteSizeValue The setting value
* @return The builder
*/
public Builder put(final String key, final ByteSizeValue byteSizeValue) {
return put(key, byteSizeValue.getStringRep());
}
/**
* Sets an | Builder |
java | elastic__elasticsearch | x-pack/plugin/searchable-snapshots/src/main/java/org/elasticsearch/xpack/searchablesnapshots/store/InMemoryNoOpCommitDirectory.java | {
"start": 1197,
"end": 5230
} | class ____ extends FilterDirectory {
private final Directory realDirectory;
private final Set<String> deletedFiles = new CopyOnWriteArraySet<>();
InMemoryNoOpCommitDirectory(Directory realDirectory) {
super(new ByteBuffersDirectory(NoLockFactory.INSTANCE));
this.realDirectory = realDirectory;
}
public Directory getRealDirectory() {
return realDirectory;
}
@Override
public String[] listAll() throws IOException {
final String[] ephemeralFiles = in.listAll();
final String[] realFiles = Arrays.stream(realDirectory.listAll())
.filter(f -> deletedFiles.contains(f) == false)
.toArray(String[]::new);
final String[] allFiles = new String[ephemeralFiles.length + realFiles.length];
System.arraycopy(ephemeralFiles, 0, allFiles, 0, ephemeralFiles.length);
System.arraycopy(realFiles, 0, allFiles, ephemeralFiles.length, realFiles.length);
return allFiles;
}
@Override
public void deleteFile(String name) throws IOException {
ensureMutable(name);
// remember that file got deleted, and blend it out when files are listed
try {
in.deleteFile(name);
} catch (NoSuchFileException | FileNotFoundException e) {
// cannot delete the segments_N file in the read-only directory, but that's ok, just ignore this
}
deletedFiles.add(name);
}
@Override
public long fileLength(String name) throws IOException {
try {
return in.fileLength(name);
} catch (NoSuchFileException | FileNotFoundException e) {
return realDirectory.fileLength(name);
}
}
@Override
public void sync(Collection<String> names) {}
@Override
public void syncMetaData() {}
@Override
public IndexOutput createOutput(String name, IOContext context) throws IOException {
ensureMutable(name);
assert notOverwritingRealSegmentsFile(name) : name;
deletedFiles.remove(name);
return super.createOutput(name, context);
}
@Override
public void rename(String source, String dest) throws IOException {
ensureMutable(source);
ensureMutable(dest);
assert notOverwritingRealSegmentsFile(dest) : dest;
super.rename(source, dest);
deletedFiles.remove(dest);
}
@Override
public IndexOutput createTempOutput(String prefix, String suffix, IOContext context) {
throw new UnsupportedOperationException();
}
@Override
public void copyFrom(Directory from, String src, String dest, IOContext context) {
throw new UnsupportedOperationException();
}
@Override
public IndexInput openInput(String name, IOContext context) throws IOException {
try {
return in.openInput(name, context);
} catch (NoSuchFileException | FileNotFoundException e) {
return realDirectory.openInput(name, context);
}
}
@Override
public void close() throws IOException {
IOUtils.close(in, realDirectory);
}
@Override
public Set<String> getPendingDeletions() throws IOException {
return super.getPendingDeletions(); // read-only realDirectory has no pending deletions
}
private static void ensureMutable(String name) {
if ((name.startsWith("segments_")
|| name.startsWith("pending_segments_")
|| name.matches("^recovery\\..*\\.segments_.*$")) == false) {
throw new ImmutableDirectoryException("file [" + name + "] is not mutable");
}
}
private boolean notOverwritingRealSegmentsFile(String name) throws IOException {
return name.startsWith("segments_") == false || Arrays.stream(realDirectory.listAll()).noneMatch(s -> s.equals(name));
}
@Override
public String toString() {
return "InMemoryNoOpCommitDirectory(" + "real=" + realDirectory + ", delegate=" + in + '}';
}
}
| InMemoryNoOpCommitDirectory |
java | google__dagger | javatests/dagger/internal/codegen/ComponentProcessorTest.java | {
"start": 16321,
"end": 17207
} | interface ____ {",
"}");
CompilerTests.daggerCompiler(
always,
testModule,
parentTest,
parentTestIncluded,
depModule,
refByDep,
parentDep,
parentDepIncluded,
componentFile)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(0);
subject.generatedSource(goldenFileRule.goldenSource("test/DaggerTestComponent"));
});
}
@Test
public void generatedTransitiveModule() {
Source rootModule =
CompilerTests.javaSource(
"test.RootModule",
"package test;",
"",
"import dagger.Module;",
"",
"@Module(includes = GeneratedModule.class)",
"final | TestComponent |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_dragoon26_1.java | {
"start": 270,
"end": 1428
} | class ____ extends TestCase {
protected void setUp() throws Exception {
ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_dragoon26_1");
}
public void test_0() throws Exception {
List<MonitorItemAlarmRule> rules = new ArrayList<MonitorItemAlarmRule>();
AlarmReceiver receiver1 = new AlarmReceiver(1L);
{
MonitorItemAlarmRule rule = new MonitorItemAlarmRule();
rule.getAlarmReceivers().add(receiver1);
rules.add(rule);
}
{
MonitorItemAlarmRule rule = new MonitorItemAlarmRule();
rule.getAlarmReceivers().add(receiver1);
rules.add(rule);
}
String text = JSON.toJSONString(rules, SerializerFeature.WriteClassName);
System.out.println(JSON.toJSONString(rules, SerializerFeature.WriteClassName, SerializerFeature.PrettyFormat));
List<MonitorItemAlarmRule> message2 = (List<MonitorItemAlarmRule>) JSON.parse(text);
System.out.println(JSON.toJSONString(message2, SerializerFeature.WriteClassName, SerializerFeature.PrettyFormat));
}
public static | Bug_for_dragoon26_1 |
java | apache__camel | components/camel-milo/src/main/java/org/apache/camel/component/milo/server/MiloServerProducer.java | {
"start": 1072,
"end": 1861
} | class ____ extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(MiloServerProducer.class);
private CamelServerItem item;
public MiloServerProducer(final MiloServerEndpoint endpoint) {
super(endpoint);
}
@Override
public MiloServerEndpoint getEndpoint() {
return (MiloServerEndpoint) super.getEndpoint();
}
@Override
protected void doStart() throws Exception {
super.doStart();
this.item = getEndpoint().getItem();
}
@Override
public void process(final Exchange exchange) throws Exception {
final Object value = exchange.getIn().getBody();
LOG.trace("Update item value - {} = {}", this.item, value);
this.item.update(value);
}
}
| MiloServerProducer |
java | google__dagger | javatests/dagger/internal/codegen/XExecutableTypesTest.java | {
"start": 14771,
"end": 15513
} | class ____ {",
" <T extends Foo> List<T> toList(Collection<T> c) { throw new RuntimeException(); }",
"}");
CompilerTests.invocationCompiler(foo, bar)
.compile(
invocation -> {
XTypeElement fooType = invocation.getProcessingEnv().requireTypeElement("test.Foo");
XMethodElement m1 = fooType.getDeclaredMethods().get(0);
XTypeElement barType = invocation.getProcessingEnv().requireTypeElement("test.Bar");
XMethodElement m2 = barType.getDeclaredMethods().get(0);
assertThat(XExecutableTypes.isSubsignature(m2, m1)).isFalse();
assertThat(XExecutableTypes.isSubsignature(m1, m2)).isFalse();
});
}
}
| Bar |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSerializationWrapper.java | {
"start": 1246,
"end": 2210
} | class ____ implements Protocol {
private final Protocol protocol;
public ProtocolSerializationWrapper(Protocol protocol) {
this.protocol = protocol;
}
@Override
public int getDefaultPort() {
return protocol.getDefaultPort();
}
@Override
public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
getFrameworkModel(invoker.getUrl().getScopeModel())
.getBeanFactory()
.getBean(PermittedSerializationKeeper.class)
.registerService(invoker.getUrl());
return protocol.export(invoker);
}
@Override
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
return protocol.refer(type, url);
}
@Override
public void destroy() {
protocol.destroy();
}
@Override
public List<ProtocolServer> getServers() {
return protocol.getServers();
}
}
| ProtocolSerializationWrapper |
java | apache__camel | components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/dto/generated/Account_IndustryEnum.java | {
"start": 1151,
"end": 3234
} | enum ____ {
// Agriculture
AGRICULTURE("Agriculture"),
// Apparel
APPAREL("Apparel"),
// Banking
BANKING("Banking"),
// Biotechnology
BIOTECHNOLOGY("Biotechnology"),
// Chemicals
CHEMICALS("Chemicals"),
// Communications
COMMUNICATIONS("Communications"),
// Construction
CONSTRUCTION("Construction"),
// Consulting
CONSULTING("Consulting"),
// Education
EDUCATION("Education"),
// Electronics
ELECTRONICS("Electronics"),
// Energy
ENERGY("Energy"),
// Engineering
ENGINEERING("Engineering"),
// Entertainment
ENTERTAINMENT("Entertainment"),
// Environmental
ENVIRONMENTAL("Environmental"),
// Finance
FINANCE("Finance"),
// Food & Beverage
FOOD___BEVERAGE("Food & Beverage"),
// Government
GOVERNMENT("Government"),
// Healthcare
HEALTHCARE("Healthcare"),
// Hospitality
HOSPITALITY("Hospitality"),
// Insurance
INSURANCE("Insurance"),
// Machinery
MACHINERY("Machinery"),
// Manufacturing
MANUFACTURING("Manufacturing"),
// Media
MEDIA("Media"),
// Not For Profit
NOT_FOR_PROFIT("Not For Profit"),
// Other
OTHER("Other"),
// Recreation
RECREATION("Recreation"),
// Retail
RETAIL("Retail"),
// Shipping
SHIPPING("Shipping"),
// Technology
TECHNOLOGY("Technology"),
// Telecommunications
TELECOMMUNICATIONS("Telecommunications"),
// Transportation
TRANSPORTATION("Transportation"),
// Utilities
UTILITIES("Utilities");
final String value;
private Account_IndustryEnum(String value) {
this.value = value;
}
@JsonValue
public String value() {
return this.value;
}
@JsonCreator
public static Account_IndustryEnum fromValue(String value) {
for (Account_IndustryEnum e : Account_IndustryEnum.values()) {
if (e.value.equals(value)) {
return e;
}
}
throw new IllegalArgumentException(value);
}
}
| Account_IndustryEnum |
java | quarkusio__quarkus | extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/TemplatePathBuildItem.java | {
"start": 3817,
"end": 6324
} | class ____ {
private String path;
private String content;
private Path fullPath;
private URI source;
private String extensionInfo;
private int priority = BUILD_ITEM_PRIORITY;
/**
* Set the path relative to the template root. The {@code /} is used as a path separator.
* <p>
* The path must be unique, i.e. if there are multiple templates with the same path then the template analysis fails
* during build.
*
* @param path
* @return self
*/
public Builder path(String path) {
this.path = Objects.requireNonNull(path);
return this;
}
/**
* Set the content of the template.
*
* @param content
* @return self
*/
public Builder content(String content) {
this.content = Objects.requireNonNull(content);
return this;
}
/**
* Set the full path of the template for templates that are backed by a file.
*
* @param fullPath
* @return self
*/
public Builder fullPath(Path fullPath) {
this.fullPath = Objects.requireNonNull(fullPath);
return this;
}
/**
* Set the source path of the template.
*
* @param source
* @return self
*/
public Builder source(URI source) {
this.source = source;
return this;
}
/**
* Set the extension info for templates that are not backed by a file.
*
* @param info
* @return self
*/
public Builder extensionInfo(String info) {
this.extensionInfo = info;
return this;
}
/**
* Set the priority of the template.
*
* @param priority
* @return self
* @see QuteConfig#duplicitTemplatesStrategy()
*/
public Builder priority(int priority) {
this.priority = priority;
return this;
}
public TemplatePathBuildItem build() {
if (fullPath == null && extensionInfo == null) {
throw new IllegalStateException("Templates that are not backed by a file must provide extension info");
}
return new TemplatePathBuildItem(path, content, fullPath, extensionInfo, priority, source);
}
}
}
| Builder |
java | netty__netty | handler/src/main/java/io/netty/handler/ssl/OpenSslInternalSession.java | {
"start": 874,
"end": 3367
} | interface ____ extends OpenSslSession {
/**
* Called on a handshake session before being exposed to a {@link javax.net.ssl.TrustManager}.
* Session data must be cleared by this call.
*/
void prepareHandshake();
/**
* Return the {@link OpenSslSessionId} that can be used to identify this session.
*/
OpenSslSessionId sessionId();
/**
* Set the local certificate chain that is used. It is not expected that this array will be changed at all
* and so its ok to not copy the array.
*/
void setLocalCertificate(Certificate[] localCertificate);
/**
* Set the details for the session which might come from a cache.
*
* @param creationTime the time at which the session was created.
* @param lastAccessedTime the time at which the session was last accessed via the session infrastructure (cache).
* @param id the {@link OpenSslSessionId}
* @param keyValueStorage the key value store. See {@link #keyValueStorage()}.
*/
void setSessionDetails(long creationTime, long lastAccessedTime, OpenSslSessionId id,
Map<String, Object> keyValueStorage);
/**
* Return the underlying {@link Map} that is used by the following methods:
*
* <ul>
* <li>{@link #putValue(String, Object)}</li>
* <li>{@link #removeValue(String)}</li>
* <li>{@link #getValue(String)}</li>
* <li> {@link #getValueNames()}</li>
* </ul>
*
* The {@link Map} must be thread-safe!
*
* @return storage
*/
Map<String, Object> keyValueStorage();
/**
* Set the last access time which will be returned by {@link #getLastAccessedTime()}.
*
* @param time the time
*/
void setLastAccessedTime(long time);
/**
* Expand (or increase) the value returned by {@link #getApplicationBufferSize()} if necessary.
* <p>
* This is only called in a synchronized block, so no need to use atomic operations.
* @param packetLengthDataOnly The packet size which exceeds the current {@link #getApplicationBufferSize()}.
*/
void tryExpandApplicationBufferSize(int packetLengthDataOnly);
/**
* Called once the handshake has completed.
*/
void handshakeFinished(byte[] id, String cipher, String protocol, byte[] peerCertificate,
byte[][] peerCertificateChain, long creationTime, long timeout) throws SSLException;
}
| OpenSslInternalSession |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialContainsCartesianSourceAndSourceEvaluator.java | {
"start": 3871,
"end": 4730
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory left;
private final EvalOperator.ExpressionEvaluator.Factory right;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory left,
EvalOperator.ExpressionEvaluator.Factory right) {
this.source = source;
this.left = left;
this.right = right;
}
@Override
public SpatialContainsCartesianSourceAndSourceEvaluator get(DriverContext context) {
return new SpatialContainsCartesianSourceAndSourceEvaluator(source, left.get(context), right.get(context), context);
}
@Override
public String toString() {
return "SpatialContainsCartesianSourceAndSourceEvaluator[" + "left=" + left + ", right=" + right + "]";
}
}
}
| Factory |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/EqualsWrongThingTest.java | {
"start": 4636,
"end": 5201
} | class ____ {
private Object a;
private Object b;
@Override
public boolean equals(Object o) {
Test that = (Test) o;
// BUG: Diagnostic contains: comparison between `a` and `b`
return a.equals(that.b) && b == that.b;
}
}
""")
.doTest();
}
@Test
public void negativeArraysEquals() {
helper
.addSourceLines(
"Test.java",
"""
import java.util.Arrays;
| Test |
java | spring-projects__spring-boot | module/spring-boot-webclient/src/main/java/org/springframework/boot/webclient/WebClientCustomizer.java | {
"start": 755,
"end": 972
} | interface ____ can be used to customize a
* {@link org.springframework.web.reactive.function.client.WebClient.Builder
* WebClient.Builder}.
*
* @author Brian Clozel
* @since 4.0.0
*/
@FunctionalInterface
public | that |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java | {
"start": 1828,
"end": 8775
} | class ____ {
private static final Object[] NO_PARAMS = {};
private static final String[] NO_SIGNATURE = {};
private final TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(new TestJmxOperation());
private final TestJmxOperationResponseMapper responseMapper = new TestJmxOperationResponseMapper();
@Test
@SuppressWarnings("NullAway") // Test null check
void createWhenResponseMapperIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new EndpointMBean(null, null, mock(ExposableJmxEndpoint.class)))
.withMessageContaining("'responseMapper' must not be null");
}
@Test
@SuppressWarnings("NullAway") // Test null check
void createWhenEndpointIsNullShouldThrowException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new EndpointMBean(mock(JmxOperationResponseMapper.class), null, null))
.withMessageContaining("'endpoint' must not be null");
}
@Test
void getMBeanInfoShouldReturnMBeanInfo() {
EndpointMBean bean = createEndpointMBean();
MBeanInfo info = bean.getMBeanInfo();
assertThat(info.getDescription()).isEqualTo("MBean operations for endpoint test");
}
@Test
void invokeShouldInvokeJmxOperation() throws MBeanException, ReflectionException {
EndpointMBean bean = createEndpointMBean();
Object result = bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE);
assertThat(result).isEqualTo("result");
}
@Test
void invokeWhenOperationFailedShouldTranslateException() {
TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(new TestJmxOperation((arguments) -> {
throw new FatalBeanException("test failure");
}));
EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint);
assertThatExceptionOfType(MBeanException.class)
.isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE))
.withCauseInstanceOf(IllegalStateException.class)
.withMessageContaining("test failure");
}
@Test
void invokeWhenOperationFailedWithJdkExceptionShouldReuseException() {
TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(new TestJmxOperation((arguments) -> {
throw new UnsupportedOperationException("test failure");
}));
EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint);
assertThatExceptionOfType(MBeanException.class)
.isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE))
.withCauseInstanceOf(UnsupportedOperationException.class)
.withMessageContaining("test failure");
}
@Test
void invokeWhenActionNameIsNotAnOperationShouldThrowException() {
EndpointMBean bean = createEndpointMBean();
assertThatExceptionOfType(ReflectionException.class)
.isThrownBy(() -> bean.invoke("missingOperation", NO_PARAMS, NO_SIGNATURE))
.withCauseInstanceOf(IllegalArgumentException.class)
.withMessageContaining("no operation named missingOperation");
}
@Test
void invokeShouldInvokeJmxOperationWithBeanClassLoader() throws ReflectionException, MBeanException {
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(
new TestJmxOperation((arguments) -> ClassUtils.getDefaultClassLoader()));
URLClassLoader beanClassLoader = new URLClassLoader(new URL[0], getClass().getClassLoader());
EndpointMBean bean = new EndpointMBean(this.responseMapper, beanClassLoader, endpoint);
Object result = bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE);
assertThat(result).isEqualTo(beanClassLoader);
assertThat(Thread.currentThread().getContextClassLoader()).isEqualTo(originalClassLoader);
}
@Test
void invokeWhenOperationIsInvalidShouldThrowException() {
TestJmxOperation operation = new TestJmxOperation() {
@Override
public Object invoke(InvocationContext context) {
throw new InvalidEndpointRequestException("test failure", "test");
}
};
TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(operation);
EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint);
assertThatExceptionOfType(ReflectionException.class)
.isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE))
.withRootCauseInstanceOf(IllegalArgumentException.class)
.withMessageContaining("test failure");
}
@Test
void invokeWhenMonoResultShouldBlockOnMono() throws MBeanException, ReflectionException {
TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(
new TestJmxOperation((arguments) -> Mono.just("monoResult")));
EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint);
Object result = bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE);
assertThat(result).isEqualTo("monoResult");
}
@Test
void invokeWhenFluxResultShouldCollectToMonoListAndBlockOnMono() throws MBeanException, ReflectionException {
TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(
new TestJmxOperation((arguments) -> Flux.just("flux", "result")));
EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint);
Object result = bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.LIST).containsExactly("flux", "result");
}
@Test
void invokeShouldCallResponseMapper() throws MBeanException, ReflectionException {
TestJmxOperationResponseMapper responseMapper = spy(this.responseMapper);
EndpointMBean bean = new EndpointMBean(responseMapper, null, this.endpoint);
bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE);
then(responseMapper).should().mapResponseType(String.class);
then(responseMapper).should().mapResponse("result");
}
@Test
void getAttributeShouldThrowException() {
EndpointMBean bean = createEndpointMBean();
assertThatExceptionOfType(AttributeNotFoundException.class).isThrownBy(() -> bean.getAttribute("test"))
.withMessageContaining("EndpointMBeans do not support attributes");
}
@Test
void setAttributeShouldThrowException() {
EndpointMBean bean = createEndpointMBean();
assertThatExceptionOfType(AttributeNotFoundException.class)
.isThrownBy(() -> bean.setAttribute(new Attribute("test", "test")))
.withMessageContaining("EndpointMBeans do not support attributes");
}
@Test
void getAttributesShouldReturnEmptyAttributeList() {
EndpointMBean bean = createEndpointMBean();
AttributeList attributes = bean.getAttributes(new String[] { "test" });
assertThat(attributes).isEmpty();
}
@Test
void setAttributesShouldReturnEmptyAttributeList() {
EndpointMBean bean = createEndpointMBean();
AttributeList sourceAttributes = new AttributeList();
sourceAttributes.add(new Attribute("test", "test"));
AttributeList attributes = bean.setAttributes(sourceAttributes);
assertThat(attributes).isEmpty();
}
private EndpointMBean createEndpointMBean() {
return new EndpointMBean(this.responseMapper, null, this.endpoint);
}
}
| EndpointMBeanTests |
java | spring-projects__spring-security | oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilder.java | {
"start": 2156,
"end": 6551
} | class ____ {
private final Map<Class<?>, Builder> builders = new LinkedHashMap<>();
private ReactiveOAuth2AuthorizedClientProviderBuilder() {
}
/**
* Returns a new {@link ReactiveOAuth2AuthorizedClientProviderBuilder} for configuring
* the supported authorization grant(s).
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public static ReactiveOAuth2AuthorizedClientProviderBuilder builder() {
return new ReactiveOAuth2AuthorizedClientProviderBuilder();
}
/**
* Configures a {@link ReactiveOAuth2AuthorizedClientProvider} to be composed with the
* {@link DelegatingReactiveOAuth2AuthorizedClientProvider}. This may be used for
* implementations of extension authorization grants.
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder provider(ReactiveOAuth2AuthorizedClientProvider provider) {
Assert.notNull(provider, "provider cannot be null");
this.builders.computeIfAbsent(provider.getClass(), (k) -> () -> provider);
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code authorization_code} grant.
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder authorizationCode() {
this.builders.computeIfAbsent(AuthorizationCodeReactiveOAuth2AuthorizedClientProvider.class,
(k) -> new AuthorizationCodeGrantBuilder());
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code refresh_token} grant.
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder refreshToken() {
this.builders.computeIfAbsent(RefreshTokenReactiveOAuth2AuthorizedClientProvider.class,
(k) -> new RefreshTokenGrantBuilder());
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code refresh_token} grant.
* @param builderConsumer a {@code Consumer} of {@link RefreshTokenGrantBuilder} used
* for further configuration
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder refreshToken(
Consumer<RefreshTokenGrantBuilder> builderConsumer) {
RefreshTokenGrantBuilder builder = (RefreshTokenGrantBuilder) this.builders.computeIfAbsent(
RefreshTokenReactiveOAuth2AuthorizedClientProvider.class, (k) -> new RefreshTokenGrantBuilder());
builderConsumer.accept(builder);
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code client_credentials} grant.
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder clientCredentials() {
this.builders.computeIfAbsent(ClientCredentialsReactiveOAuth2AuthorizedClientProvider.class,
(k) -> new ClientCredentialsGrantBuilder());
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Configures support for the {@code client_credentials} grant.
* @param builderConsumer a {@code Consumer} of {@link ClientCredentialsGrantBuilder}
* used for further configuration
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
*/
public ReactiveOAuth2AuthorizedClientProviderBuilder clientCredentials(
Consumer<ClientCredentialsGrantBuilder> builderConsumer) {
ClientCredentialsGrantBuilder builder = (ClientCredentialsGrantBuilder) this.builders.computeIfAbsent(
ClientCredentialsReactiveOAuth2AuthorizedClientProvider.class,
(k) -> new ClientCredentialsGrantBuilder());
builderConsumer.accept(builder);
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
}
/**
* Builds an instance of {@link DelegatingReactiveOAuth2AuthorizedClientProvider}
* composed of one or more {@link ReactiveOAuth2AuthorizedClientProvider}(s).
* @return the {@link DelegatingReactiveOAuth2AuthorizedClientProvider}
*/
public ReactiveOAuth2AuthorizedClientProvider build() {
List<ReactiveOAuth2AuthorizedClientProvider> authorizedClientProviders = this.builders.values()
.stream()
.map(Builder::build)
.collect(Collectors.toList());
return new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProviders);
}
| ReactiveOAuth2AuthorizedClientProviderBuilder |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/internal/BasicSqmPathSource.java | {
"start": 719,
"end": 2509
} | class ____<J>
extends AbstractSqmPathSource<J>
implements ReturnableType<J> {
private final JavaType<?> relationalJavaType;
private final boolean isGeneric;
public BasicSqmPathSource(
String localPathName,
@Nullable SqmPathSource<J> pathModel,
BasicDomainType<J> domainType,
JavaType<?> relationalJavaType,
BindableType jpaBindableType,
boolean isGeneric) {
super( localPathName, pathModel, domainType, jpaBindableType );
this.relationalJavaType = relationalJavaType;
this.isGeneric = isGeneric;
}
@Override
public String getTypeName() {
return super.getTypeName();
}
// @Override
// public SqmDomainType<J> getSqmType() {
// return getPathType();
// }
@Override
public @Nullable SqmPathSource<?> findSubPathSource(String name) {
String path = pathModel.getPathName();
String pathDesc = path == null || path.startsWith( "{" ) ? " " : " '" + pathModel.getPathName() + "' ";
throw new TerminalPathException( "Terminal path" + pathDesc + "has no attribute '" + name + "'" );
}
@Override
public SqmPath<J> createSqmPath(SqmPath<?> lhs, @Nullable SqmPathSource<?> intermediatePathSource) {
return new SqmBasicValuedSimplePath<>(
PathHelper.append( lhs, this, intermediatePathSource ),
pathModel,
lhs,
lhs.nodeBuilder()
);
}
@Override
public PersistenceType getPersistenceType() {
return BASIC;
}
@Override
public Class<J> getJavaType() {
return getExpressibleJavaType().getJavaTypeClass();
}
@Override
public JavaType<?> getRelationalJavaType() {
return relationalJavaType;
}
@Override
public boolean isGeneric() {
return isGeneric;
}
@Override
public String toString() {
return "BasicSqmPathSource(" +
getPathName() + " : " + getJavaType().getSimpleName() +
")";
}
}
| BasicSqmPathSource |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/erasurecode/rawcoder/TestDecodingValidator.java | {
"start": 1706,
"end": 9931
} | class ____ extends TestRawCoderBase {
private DecodingValidator validator;
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{RSRawErasureCoderFactory.class, 6, 3, new int[]{1}, new int[]{}},
{RSRawErasureCoderFactory.class, 6, 3, new int[]{3}, new int[]{0}},
{RSRawErasureCoderFactory.class, 6, 3, new int[]{2, 4}, new int[]{1}},
{NativeRSRawErasureCoderFactory.class, 6, 3, new int[]{0}, new int[]{}},
{XORRawErasureCoderFactory.class, 10, 1, new int[]{0}, new int[]{}},
{NativeXORRawErasureCoderFactory.class, 10, 1, new int[]{0},
new int[]{}}
});
}
public void initTestDecodingValidator(
Class<? extends RawErasureCoderFactory> factoryClass, int numDataUnits,
int numParityUnits, int[] erasedDataIndexes, int[] erasedParityIndexes) {
this.encoderFactoryClass = factoryClass;
this.decoderFactoryClass = factoryClass;
this.numDataUnits = numDataUnits;
this.numParityUnits = numParityUnits;
this.erasedDataIndexes = erasedDataIndexes;
this.erasedParityIndexes = erasedParityIndexes;
setup();
}
public void setup() {
if (encoderFactoryClass == NativeRSRawErasureCoderFactory.class
|| encoderFactoryClass == NativeXORRawErasureCoderFactory.class) {
assumeTrue(ErasureCodeNative.isNativeCodeLoaded());
}
setAllowDump(false);
}
/**
* Test if the same validator can process direct and non-direct buffers.
*/
@ParameterizedTest
@MethodSource("data")
public void testValidate(Class<? extends RawErasureCoderFactory> factoryClass,
int numDataUnits, int numParityUnits, int[] erasedDataIndexes, int[] erasedParityIndexes) {
initTestDecodingValidator(factoryClass, numDataUnits, numParityUnits,
erasedDataIndexes, erasedParityIndexes);
prepare(null, numDataUnits, numParityUnits, erasedDataIndexes,
erasedParityIndexes);
testValidate(true);
testValidate(false);
}
/**
* Test if the same validator can process variable width of data for
* inputs and outputs.
*/
protected void testValidate(boolean usingDirectBuffer) {
this.usingDirectBuffer = usingDirectBuffer;
prepareCoders(false);
prepareValidator(false);
performTestValidate(baseChunkSize);
performTestValidate(baseChunkSize - 17);
performTestValidate(baseChunkSize + 18);
}
protected void prepareValidator(boolean recreate) {
if (validator == null || recreate) {
validator = new DecodingValidator(decoder);
}
}
protected void performTestValidate(int chunkSize) {
setChunkSize(chunkSize);
prepareBufferAllocator(false);
// encode
ECChunk[] dataChunks = prepareDataChunksForEncoding();
ECChunk[] parityChunks = prepareParityChunksForEncoding();
ECChunk[] clonedDataChunks = cloneChunksWithData(dataChunks);
try {
encoder.encode(dataChunks, parityChunks);
} catch (Exception e) {
fail("Should not get Exception: " + e.getMessage());
}
// decode
backupAndEraseChunks(clonedDataChunks, parityChunks);
ECChunk[] inputChunks =
prepareInputChunksForDecoding(clonedDataChunks, parityChunks);
markChunks(inputChunks);
ensureOnlyLeastRequiredChunks(inputChunks);
ECChunk[] recoveredChunks = prepareOutputChunksForDecoding();
int[] erasedIndexes = getErasedIndexesForDecoding();
try {
decoder.decode(inputChunks, erasedIndexes, recoveredChunks);
} catch (Exception e) {
fail("Should not get Exception: " + e.getMessage());
}
// validate
restoreChunksFromMark(inputChunks);
ECChunk[] clonedInputChunks = cloneChunksWithData(inputChunks);
ECChunk[] clonedRecoveredChunks = cloneChunksWithData(recoveredChunks);
int[] clonedErasedIndexes = erasedIndexes.clone();
try {
validator.validate(clonedInputChunks, clonedErasedIndexes,
clonedRecoveredChunks);
} catch (Exception e) {
fail("Should not get Exception: " + e.getMessage());
}
// Check if input buffers' positions are moved to the end
verifyBufferPositionAtEnd(clonedInputChunks);
// Check if validator does not change recovered chunks and erased indexes
verifyChunksEqual(recoveredChunks, clonedRecoveredChunks);
assertArrayEquals(erasedIndexes, clonedErasedIndexes,
"Erased indexes should not be changed");
// Check if validator uses correct indexes for validation
List<Integer> validIndexesList =
IntStream.of(CoderUtil.getValidIndexes(inputChunks)).boxed()
.collect(Collectors.toList());
List<Integer> newValidIndexesList =
IntStream.of(validator.getNewValidIndexes()).boxed()
.collect(Collectors.toList());
List<Integer> erasedIndexesList =
IntStream.of(erasedIndexes).boxed().collect(Collectors.toList());
int newErasedIndex = validator.getNewErasedIndex();
assertTrue(newValidIndexesList.containsAll(erasedIndexesList),
"Valid indexes for validation should contain"
+ " erased indexes for decoding");
assertTrue(validIndexesList.contains(newErasedIndex),
"An erased index for validation should be contained"
+ " in valid indexes for decoding");
assertFalse(newValidIndexesList.contains(newErasedIndex),
"An erased index for validation should not be contained"
+ " in valid indexes for validation");
}
private void verifyChunksEqual(ECChunk[] chunks1, ECChunk[] chunks2) {
boolean result = Arrays.deepEquals(toArrays(chunks1), toArrays(chunks2));
assertTrue(result, "Recovered chunks should not be changed");
}
/**
* Test if validator throws {@link InvalidDecodingException} when
* a decoded output buffer is polluted.
*/
@ParameterizedTest
@MethodSource("data")
public void testValidateWithBadDecoding(Class<? extends RawErasureCoderFactory> factoryClass,
int numDataUnits, int numParityUnits, int[] erasedDataIndexes, int[] erasedParityIndexes)
throws IOException {
initTestDecodingValidator(factoryClass, numDataUnits, numParityUnits,
erasedDataIndexes, erasedParityIndexes);
prepare(null, numDataUnits, numParityUnits, erasedDataIndexes,
erasedParityIndexes);
this.usingDirectBuffer = true;
prepareCoders(true);
prepareValidator(true);
prepareBufferAllocator(false);
// encode
ECChunk[] dataChunks = prepareDataChunksForEncoding();
ECChunk[] parityChunks = prepareParityChunksForEncoding();
ECChunk[] clonedDataChunks = cloneChunksWithData(dataChunks);
try {
encoder.encode(dataChunks, parityChunks);
} catch (Exception e) {
fail("Should not get Exception: " + e.getMessage());
}
// decode
backupAndEraseChunks(clonedDataChunks, parityChunks);
ECChunk[] inputChunks =
prepareInputChunksForDecoding(clonedDataChunks, parityChunks);
markChunks(inputChunks);
ensureOnlyLeastRequiredChunks(inputChunks);
ECChunk[] recoveredChunks = prepareOutputChunksForDecoding();
int[] erasedIndexes = getErasedIndexesForDecoding();
try {
decoder.decode(inputChunks, erasedIndexes, recoveredChunks);
} catch (Exception e) {
fail("Should not get Exception: " + e.getMessage());
}
// validate
restoreChunksFromMark(inputChunks);
polluteSomeChunk(recoveredChunks);
try {
validator.validate(inputChunks, erasedIndexes, recoveredChunks);
fail("Validation should fail due to bad decoding");
} catch (InvalidDecodingException e) {
String expected = "Failed to validate decoding";
GenericTestUtils.assertExceptionContains(expected, e);
}
}
@ParameterizedTest
@MethodSource("data")
public void testIdempotentReleases(Class<? extends RawErasureCoderFactory> factoryClass,
int numDataUnits, int numParityUnits, int[] erasedDataIndexes, int[] erasedParityIndexes) {
initTestDecodingValidator(factoryClass, numDataUnits, numParityUnits,
erasedDataIndexes, erasedParityIndexes);
prepareCoders(true);
for (int i = 0; i < 3; i++) {
encoder.release();
decoder.release();
}
}
@Test
public void testIdempotentReleases() {
}
}
| TestDecodingValidator |
java | elastic__elasticsearch | libs/geo/src/test/java/org/elasticsearch/geometry/BaseGeometryTestCase.java | {
"start": 887,
"end": 4031
} | class ____<T extends Geometry> extends AbstractWireTestCase<T> {
public static final String ZorMMustIncludeThreeValuesMsg =
"When specifying 'Z' or 'M', coordinates must include three values. Only two coordinates were provided";
@Override
protected final T createTestInstance() {
boolean hasAlt = randomBoolean();
T obj = createTestInstance(hasAlt);
assertEquals(hasAlt, obj.hasZ());
return obj;
}
protected abstract T createTestInstance(boolean hasAlt);
@SuppressWarnings("unchecked")
@Override
protected T copyInstance(T instance, TransportVersion version) throws IOException {
String text = WellKnownText.toWKT(instance);
try {
return (T) WellKnownText.fromWKT(GeographyValidator.instance(true), true, text);
} catch (ParseException e) {
throw new ElasticsearchException(e);
}
}
public void testVisitor() {
testVisitor(createTestInstance());
}
public static void testVisitor(Geometry geom) {
AtomicBoolean called = new AtomicBoolean(false);
Object result = geom.visit(new GeometryVisitor<Object, RuntimeException>() {
private Object verify(Geometry geometry, String expectedClass) {
assertFalse("Visitor should be called only once", called.getAndSet(true));
assertSame(geom, geometry);
assertEquals(geometry.getClass().getName(), "org.elasticsearch.geometry." + expectedClass);
return "result";
}
@Override
public Object visit(Circle circle) {
return verify(circle, "Circle");
}
@Override
public Object visit(GeometryCollection<?> collection) {
return verify(collection, "GeometryCollection");
}
@Override
public Object visit(Line line) {
return verify(line, "Line");
}
@Override
public Object visit(LinearRing ring) {
return verify(ring, "LinearRing");
}
@Override
public Object visit(MultiLine multiLine) {
return verify(multiLine, "MultiLine");
}
@Override
public Object visit(MultiPoint multiPoint) {
return verify(multiPoint, "MultiPoint");
}
@Override
public Object visit(MultiPolygon multiPolygon) {
return verify(multiPolygon, "MultiPolygon");
}
@Override
public Object visit(Point point) {
return verify(point, "Point");
}
@Override
public Object visit(Polygon polygon) {
return verify(polygon, "Polygon");
}
@Override
public Object visit(Rectangle rectangle) {
return verify(rectangle, "Rectangle");
}
});
assertTrue("visitor wasn't called", called.get());
assertEquals("result", result);
}
}
| BaseGeometryTestCase |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/suggest/completion/context/GeoContextMapping.java | {
"start": 2355,
"end": 14230
} | class ____ extends ContextMapping<GeoQueryContext> {
public static final String FIELD_PRECISION = "precision";
public static final String FIELD_FIELDNAME = "path";
public static final int DEFAULT_PRECISION = 6;
static final String CONTEXT_VALUE = "context";
static final String CONTEXT_BOOST = "boost";
static final String CONTEXT_PRECISION = "precision";
static final String CONTEXT_NEIGHBOURS = "neighbours";
private static final DeprecationLogger deprecationLogger = DeprecationLogger.getLogger(GeoContextMapping.class);
private final int precision;
private final String fieldName;
private GeoContextMapping(String name, String fieldName, int precision) {
super(Type.GEO, name);
this.precision = precision;
this.fieldName = fieldName;
}
public String getFieldName() {
return fieldName;
}
public int getPrecision() {
return precision;
}
protected static GeoContextMapping load(String name, Map<String, Object> config) {
final GeoContextMapping.Builder builder = new GeoContextMapping.Builder(name);
if (config != null) {
final Object configPrecision = config.get(FIELD_PRECISION);
if (configPrecision != null) {
if (configPrecision instanceof Integer) {
builder.precision((Integer) configPrecision);
} else if (configPrecision instanceof Long) {
builder.precision((Long) configPrecision);
} else if (configPrecision instanceof Double) {
builder.precision((Double) configPrecision);
} else if (configPrecision instanceof Float) {
builder.precision((Float) configPrecision);
} else {
builder.precision(configPrecision.toString());
}
config.remove(FIELD_PRECISION);
}
final Object fieldName = config.get(FIELD_FIELDNAME);
if (fieldName != null) {
builder.field(fieldName.toString());
config.remove(FIELD_FIELDNAME);
}
}
return builder.build();
}
@Override
protected XContentBuilder toInnerXContent(XContentBuilder builder, Params params) throws IOException {
builder.field(FIELD_PRECISION, precision);
if (fieldName != null) {
builder.field(FIELD_FIELDNAME, fieldName);
}
return builder;
}
/**
* Parse a set of {@link CharSequence} contexts at index-time.
* Acceptable formats:
*
* <ul>
* <li>Array: <pre>[<i><GEO POINT></i>, ..]</pre></li>
* <li>String/Object/Array: <pre>"GEO POINT"</pre></li>
* </ul>
*
* see {@code GeoPoint(String)} for GEO POINT
*/
@Override
public Set<String> parseContext(DocumentParserContext documentParserContext, XContentParser parser) throws IOException,
ElasticsearchParseException {
final Set<String> contexts = new HashSet<>();
Token token = parser.currentToken();
if (token == Token.START_ARRAY) {
token = parser.nextToken();
// Test if value is a single point in <code>[lon, lat]</code> format
if (token == Token.VALUE_NUMBER) {
double lon = parser.doubleValue();
if (parser.nextToken() == Token.VALUE_NUMBER) {
double lat = parser.doubleValue();
if (parser.nextToken() == Token.END_ARRAY) {
contexts.add(stringEncode(lon, lat, precision));
} else {
throw new ElasticsearchParseException("only two values [lon, lat] expected");
}
} else {
throw new ElasticsearchParseException("latitude must be a numeric value");
}
} else {
while (token != Token.END_ARRAY) {
GeoPoint point = GeoUtils.parseGeoPoint(parser);
contexts.add(stringEncode(point.getLon(), point.getLat(), precision));
token = parser.nextToken();
}
}
} else if (token == Token.VALUE_STRING) {
final String geoHash = parser.text();
final CharSequence truncatedGeoHash = geoHash.subSequence(0, Math.min(geoHash.length(), precision));
contexts.add(truncatedGeoHash.toString());
} else {
// or a single location
GeoPoint point = GeoUtils.parseGeoPoint(parser);
contexts.add(stringEncode(point.getLon(), point.getLat(), precision));
}
return contexts;
}
@Override
public Set<String> parseContext(LuceneDocument document) {
final Set<String> geohashes = new HashSet<>();
if (fieldName != null) {
List<IndexableField> fields = document.getFields(fieldName);
GeoPoint spare = new GeoPoint();
for (IndexableField field : fields) {
if (field instanceof StringField) {
spare.resetFromString(field.stringValue());
geohashes.add(spare.geohash());
} else if (field instanceof LatLonDocValuesField || field instanceof GeoPointFieldMapper.LatLonPointWithDocValues) {
spare.resetFromEncoded(field.numericValue().longValue());
geohashes.add(spare.geohash());
} else if (field instanceof LatLonPoint) {
BytesRef bytes = field.binaryValue();
spare.reset(
NumericUtils.sortableBytesToInt(bytes.bytes, bytes.offset),
NumericUtils.sortableBytesToInt(bytes.bytes, bytes.offset + Integer.BYTES)
);
geohashes.add(spare.geohash());
}
}
}
Set<String> locations = new HashSet<>();
for (String geohash : geohashes) {
int precision = Math.min(this.precision, geohash.length());
String truncatedGeohash = geohash.substring(0, precision);
locations.add(truncatedGeohash);
}
return locations;
}
@Override
protected GeoQueryContext fromXContent(XContentParser parser) throws IOException {
return GeoQueryContext.fromXContent(parser);
}
/**
* Parse a list of {@link GeoQueryContext}
* using <code>parser</code>. A QueryContexts accepts one of the following forms:
*
* <ul>
* <li>Object: GeoQueryContext</li>
* <li>String: GeoQueryContext value with boost=1 precision=PRECISION neighbours=[PRECISION]</li>
* <li>Array: <pre>[GeoQueryContext, ..]</pre></li>
* </ul>
*
* A GeoQueryContext has one of the following forms:
* <ul>
* <li>Object:
* <ul>
* <li><pre>GEO POINT</pre></li>
* <li><pre>{"lat": <i><double></i>, "lon": <i><double></i>, "precision":
* <i><int></i>, "neighbours": <i><[int, ..]></i>}</pre></li>
* <li><pre>{"context": <i><string></i>, "boost": <i><int></i>, "precision":
* <i><int></i>, "neighbours": <i><[int, ..]></i>}</pre></li>
* <li><pre>{"context": <i><GEO POINT></i>, "boost": <i><int></i>, "precision":
* <i><int></i>, "neighbours": <i><[int, ..]></i>}</pre></li>
* </ul>
* <li>String: <pre>GEO POINT</pre></li>
* </ul>
* see {@code GeoPoint(String)} for GEO POINT
*/
@Override
public List<InternalQueryContext> toInternalQueryContexts(List<GeoQueryContext> queryContexts) {
List<InternalQueryContext> internalQueryContextList = new ArrayList<>();
for (GeoQueryContext queryContext : queryContexts) {
int minPrecision = Math.min(this.precision, queryContext.getPrecision());
GeoPoint point = queryContext.getGeoPoint();
final Collection<String> locations = new HashSet<>();
String geoHash = stringEncode(point.getLon(), point.getLat(), minPrecision);
locations.add(geoHash);
if (queryContext.getNeighbours().isEmpty() && geoHash.length() == this.precision) {
addNeighbors(geoHash, locations);
} else if (queryContext.getNeighbours().isEmpty() == false) {
queryContext.getNeighbours()
.stream()
.filter(neighbourPrecision -> neighbourPrecision < geoHash.length())
.forEach(neighbourPrecision -> {
String truncatedGeoHash = geoHash.substring(0, neighbourPrecision);
locations.add(truncatedGeoHash);
addNeighbors(truncatedGeoHash, locations);
});
}
internalQueryContextList.addAll(
locations.stream()
.map(location -> new InternalQueryContext(location, queryContext.getBoost(), location.length() < this.precision))
.toList()
);
}
return internalQueryContextList;
}
@Override
public void validateReferences(IndexVersion indexVersionCreated, Function<String, MappedFieldType> fieldResolver) {
if (fieldName != null) {
MappedFieldType mappedFieldType = fieldResolver.apply(fieldName);
if (mappedFieldType == null) {
if (indexVersionCreated.before(IndexVersions.V_7_0_0)) {
deprecationLogger.warn(
DeprecationCategory.MAPPINGS,
"geo_context_mapping",
"field [{}] referenced in context [{}] is not defined in the mapping",
fieldName,
name
);
} else {
throw new ElasticsearchParseException(
"field [{}] referenced in context [{}] is not defined in the mapping",
fieldName,
name
);
}
} else if (GeoPointFieldMapper.CONTENT_TYPE.equals(mappedFieldType.typeName()) == false) {
if (indexVersionCreated.before(IndexVersions.V_7_0_0)) {
deprecationLogger.warn(
DeprecationCategory.MAPPINGS,
"geo_context_mapping",
"field [{}] referenced in context [{}] must be mapped to geo_point, found [{}]",
fieldName,
name,
mappedFieldType.typeName()
);
} else {
throw new ElasticsearchParseException(
"field [{}] referenced in context [{}] must be mapped to geo_point, found [{}]",
fieldName,
name,
mappedFieldType.typeName()
);
}
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (super.equals(o) == false) return false;
GeoContextMapping that = (GeoContextMapping) o;
if (precision != that.precision) return false;
return Objects.equals(fieldName, that.fieldName);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), precision, fieldName);
}
public static | GeoContextMapping |
java | spring-projects__spring-boot | module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/init/PropertiesBasedDataSourceScriptDatabaseInitializer.java | {
"start": 1214,
"end": 3878
} | class ____<T extends DatabaseInitializationProperties>
extends DataSourceScriptDatabaseInitializer {
/**
* Create a new {@link PropertiesBasedDataSourceScriptDatabaseInitializer} instance.
* @param dataSource the data source
* @param properties the configuration properties
* @see #getSettings
*/
public PropertiesBasedDataSourceScriptDatabaseInitializer(DataSource dataSource, T properties) {
this(dataSource, properties, Collections.emptyMap());
}
/**
* Create a new {@link PropertiesBasedDataSourceScriptDatabaseInitializer} instance.
* @param dataSource the data source
* @param properties the configuration properties
* @param driverMappings the driver mappings
* @see #getSettings
*/
public PropertiesBasedDataSourceScriptDatabaseInitializer(DataSource dataSource, T properties,
Map<DatabaseDriver, String> driverMappings) {
super(dataSource, getSettings(dataSource, properties, driverMappings));
}
/**
* Adapts {@link DatabaseInitializationProperties configuration properties} to
* {@link DatabaseInitializationSettings} replacing any {@literal @@platform@@}
* placeholders.
* @param dataSource the data source
* @param properties the configuration properties
* @param driverMappings the driver mappings
* @param <T> the {@link DatabaseInitializationProperties} type being used
* @return a new {@link DatabaseInitializationSettings} instance
*/
private static <T extends DatabaseInitializationProperties> DatabaseInitializationSettings getSettings(
DataSource dataSource, T properties, Map<DatabaseDriver, String> driverMappings) {
DatabaseInitializationSettings settings = new DatabaseInitializationSettings();
settings.setSchemaLocations(resolveSchemaLocations(dataSource, properties, driverMappings));
settings.setMode(properties.getInitializeSchema());
settings.setContinueOnError(properties.isContinueOnError());
return settings;
}
private static <T extends DatabaseInitializationProperties> List<String> resolveSchemaLocations(
DataSource dataSource, T properties, Map<DatabaseDriver, String> driverMappings) {
PlatformPlaceholderDatabaseDriverResolver platformResolver = new PlatformPlaceholderDatabaseDriverResolver();
for (Map.Entry<DatabaseDriver, String> entry : driverMappings.entrySet()) {
platformResolver = platformResolver.withDriverPlatform(entry.getKey(), entry.getValue());
}
if (StringUtils.hasText(properties.getPlatform())) {
return platformResolver.resolveAll(properties.getPlatform(), properties.getSchema());
}
return platformResolver.resolveAll(dataSource, properties.getSchema());
}
}
| PropertiesBasedDataSourceScriptDatabaseInitializer |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/resource/jdbc/internal/LogicalConnectionManagedImpl.java | {
"start": 1589,
"end": 1661
} | class ____ used in the wrong way.
*
* @author Steve Ebersole
*/
public | is |
java | dropwizard__dropwizard | dropwizard-metrics/src/main/java/io/dropwizard/metrics/common/ReporterFactory.java | {
"start": 451,
"end": 723
} | class ____ implements {@link ReporterFactory}.</li>
* <li>Annotate it with {@code @JsonTypeName} and give it a unique type name.</li>
* <li>Add a {@code META-INF/services/io.dropwizard.metrics.common.ReporterFactory}
* file with your implementation's full | which |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/results/internal/complete/ModelPartReferenceBasic.java | {
"start": 253,
"end": 372
} | interface ____ extends ModelPartReference {
@Override
BasicValuedModelPart getReferencedPart();
}
| ModelPartReferenceBasic |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/repository/SchemaResolveVisitorFactory.java | {
"start": 12522,
"end": 15101
} | class ____ extends OdpsASTVisitorAdapter implements SchemaResolveVisitor {
private int options;
private SchemaRepository repository;
private Context context;
public OdpsResolveVisitor(SchemaRepository repository, int options) {
this.repository = repository;
this.options = options;
}
public boolean visit(OdpsSelectQueryBlock x) {
resolve(this, x);
return false;
}
public boolean visit(SQLSelectItem x) {
SQLExpr expr = x.getExpr();
if (expr instanceof SQLIdentifierExpr) {
resolveIdent(this, (SQLIdentifierExpr) expr);
return false;
}
if (expr instanceof SQLPropertyExpr) {
resolve(this, (SQLPropertyExpr) expr);
return false;
}
return true;
}
public boolean visit(OdpsCreateTableStatement x) {
resolve(this, x);
return false;
}
public boolean visit(HiveInsert x) {
Context ctx = createContext(x);
SQLExprTableSource tableSource = x.getTableSource();
if (tableSource != null) {
ctx.setTableSource(x.getTableSource());
visit(tableSource);
}
List<SQLAssignItem> partitions = x.getPartitions();
if (partitions != null) {
for (SQLAssignItem item : partitions) {
item.accept(this);
}
}
SQLSelect select = x.getQuery();
if (select != null) {
visit(select);
}
popContext();
return false;
}
public boolean visit(HiveInsertStatement x) {
resolve(this, x);
return false;
}
@Override
public boolean isEnabled(Option option) {
return (options & option.mask) != 0;
}
public int getOptions() {
return options;
}
@Override
public Context getContext() {
return context;
}
public Context createContext(SQLObject object) {
return this.context = new Context(object, context);
}
@Override
public void popContext() {
if (context != null) {
context = context.parent;
}
}
public SchemaRepository getRepository() {
return repository;
}
}
static | OdpsResolveVisitor |
java | quarkusio__quarkus | independent-projects/tools/analytics-common/src/main/java/io/quarkus/analytics/dto/segment/TrackEventType.java | {
"start": 50,
"end": 98
} | enum ____ {
BUILD,
DEV_MODE
}
| TrackEventType |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java | {
"start": 20887,
"end": 21484
} | class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().hasRole("USER")
)
.formLogin(withDefaults())
.rememberMe((rememberMe) -> rememberMe
.rememberMeCookieDomain("spring.io")
);
return http.build();
// @formatter:on
}
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
@Configuration
@EnableWebSecurity
static | RememberMeCookieDomainInLambdaConfig |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/inheritance/joined/Pool.java | {
"start": 926,
"end": 1576
} | class ____ {
@Id @GeneratedValue
private Integer id;
@Embedded
private PoolAddress address;
@Embedded
@AttributeOverride(name = "address", column = @Column(table = "POOL_ADDRESS_2"))
private PoolAddress secondaryAddress;
public PoolAddress getAddress() {
return address;
}
public void setAddress(PoolAddress address) {
this.address = address;
}
public PoolAddress getSecondaryAddress() {
return secondaryAddress;
}
public void setSecondaryAddress(PoolAddress secondaryAddress) {
this.secondaryAddress = secondaryAddress;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
| Pool |
java | spring-projects__spring-framework | spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/reactive/AbstractNamedValueMethodArgumentResolver.java | {
"start": 1525,
"end": 2129
} | class ____ resolve method arguments from a named value, for example,
* message headers or destination variables. Named values could have one or more
* of a name, a required flag, and a default value.
*
* <p>Subclasses only need to define specific steps such as how to obtain named
* value details from a method parameter, how to resolve to argument values, or
* how to handle missing values.
*
* <p>A default value string can contain ${...} placeholders and Spring
* Expression Language {@code #{...}} expressions which will be resolved if a
* {@link ConfigurableBeanFactory} is supplied to the | to |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/DefaultCheckpointStatsTracker.java | {
"start": 32032,
"end": 32219
} | class ____ implements Gauge<Long> {
@Override
public Long getValue() {
return counts.getTotalNumberOfCheckpoints();
}
}
private | CheckpointsCounter |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/protocol/SharedLockUnitTests.java | {
"start": 298,
"end": 1807
} | class ____ {
@Test
public void safety_on_reentrant_lock_exclusive_on_writers() throws InterruptedException {
final SharedLock sharedLock = new SharedLock();
CountDownLatch cnt = new CountDownLatch(1);
try {
sharedLock.incrementWriters();
String result = sharedLock.doExclusive(() -> {
return sharedLock.doExclusive(() -> {
return "ok";
});
});
if ("ok".equals(result)) {
cnt.countDown();
}
} finally {
sharedLock.decrementWriters();
}
boolean await = cnt.await(1, TimeUnit.SECONDS);
Assertions.assertTrue(await);
// verify writers won't be negative after finally decrementWriters
String result = sharedLock.doExclusive(() -> {
return sharedLock.doExclusive(() -> {
return "ok";
});
});
Assertions.assertEquals("ok", result);
// and other writers should be passed after exclusive lock released
CountDownLatch cntOtherThread = new CountDownLatch(1);
new Thread(() -> {
try {
sharedLock.incrementWriters();
cntOtherThread.countDown();
} finally {
sharedLock.decrementWriters();
}
}).start();
await = cntOtherThread.await(1, TimeUnit.SECONDS);
Assertions.assertTrue(await);
}
}
| SharedLockUnitTests |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ParamsRequestConditionTests.java | {
"start": 1084,
"end": 5424
} | class ____ {
@Test
void paramEquals() {
assertThat(new ParamsRequestCondition("foo")).isEqualTo(new ParamsRequestCondition("foo"));
assertThat(new ParamsRequestCondition("foo")).isNotEqualTo(new ParamsRequestCondition("bar"));
assertThat(new ParamsRequestCondition("foo")).isNotEqualTo(new ParamsRequestCondition("FOO"));
assertThat(new ParamsRequestCondition("foo=bar")).isEqualTo(new ParamsRequestCondition("foo=bar"));
assertThat(new ParamsRequestCondition("foo=bar")).isNotEqualTo(new ParamsRequestCondition("FOO=bar"));
}
@Test
void paramPresent() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("foo", "");
assertThat(new ParamsRequestCondition("foo").getMatchingCondition(request)).isNotNull();
}
@Test // SPR-15831
void paramPresentNullValue() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("foo", (String) null);
assertThat(new ParamsRequestCondition("foo").getMatchingCondition(request)).isNotNull();
}
@Test
void paramPresentNoMatch() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("bar", "");
assertThat(new ParamsRequestCondition("foo").getMatchingCondition(request)).isNull();
}
@Test
void paramNotPresent() {
ParamsRequestCondition condition = new ParamsRequestCondition("!foo");
MockHttpServletRequest request = new MockHttpServletRequest();
assertThat(condition.getMatchingCondition(request)).isNotNull();
}
@Test
void paramValueMatch() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("foo", "bar");
assertThat(new ParamsRequestCondition("foo=bar").getMatchingCondition(request)).isNotNull();
}
@Test
void paramValueNoMatch() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("foo", "bazz");
assertThat(new ParamsRequestCondition("foo=bar").getMatchingCondition(request)).isNull();
}
@Test
void compareTo() {
MockHttpServletRequest request = new MockHttpServletRequest();
ParamsRequestCondition condition1 = new ParamsRequestCondition("foo", "bar", "baz");
ParamsRequestCondition condition2 = new ParamsRequestCondition("foo=a", "bar");
int result = condition1.compareTo(condition2, request);
assertThat(result).as("Invalid comparison result: " + result).isLessThan(0);
result = condition2.compareTo(condition1, request);
assertThat(result).as("Invalid comparison result: " + result).isGreaterThan(0);
}
@Test // SPR-16674
void compareToWithMoreSpecificMatchByValue() {
MockHttpServletRequest request = new MockHttpServletRequest();
ParamsRequestCondition condition1 = new ParamsRequestCondition("response_type=code");
ParamsRequestCondition condition2 = new ParamsRequestCondition("response_type");
int result = condition1.compareTo(condition2, request);
assertThat(result).as("Invalid comparison result: " + result).isLessThan(0);
}
@Test
void compareToWithNegatedMatch() {
MockHttpServletRequest request = new MockHttpServletRequest();
ParamsRequestCondition condition1 = new ParamsRequestCondition("response_type!=code");
ParamsRequestCondition condition2 = new ParamsRequestCondition("response_type");
assertThat(condition1.compareTo(condition2, request)).as("Negated match should not count as more specific").isEqualTo(0);
}
@Test
void combineWithOtherEmpty() {
ParamsRequestCondition condition1 = new ParamsRequestCondition("foo=bar");
ParamsRequestCondition condition2 = new ParamsRequestCondition();
ParamsRequestCondition result = condition1.combine(condition2);
assertThat(result).isEqualTo(condition1);
}
@Test
void combineWithThisEmpty() {
ParamsRequestCondition condition1 = new ParamsRequestCondition();
ParamsRequestCondition condition2 = new ParamsRequestCondition("foo=bar");
ParamsRequestCondition result = condition1.combine(condition2);
assertThat(result).isEqualTo(condition2);
}
@Test
void combine() {
ParamsRequestCondition condition1 = new ParamsRequestCondition("foo=bar");
ParamsRequestCondition condition2 = new ParamsRequestCondition("foo=baz");
ParamsRequestCondition result = condition1.combine(condition2);
Collection<ParamExpression> conditions = result.getContent();
assertThat(conditions).hasSize(2);
}
}
| ParamsRequestConditionTests |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/annotation/DefaultImplementation.java | {
"start": 2369,
"end": 2690
} | interface ____ {
/**
* @return The bean type that is the default implementation
*/
@AliasFor(member = "name")
Class<?> value() default void.class;
/**
* @return The fully qualified bean type name that is the default implementation
*/
String name() default "";
}
| DefaultImplementation |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestVersionUtil.java | {
"start": 1004,
"end": 4606
} | class ____ {
@Test
public void testCompareVersions() {
// Equal versions are equal.
assertEquals(0, VersionUtil.compareVersions("2.0.0", "2.0.0"));
assertEquals(0, VersionUtil.compareVersions("2.0.0a", "2.0.0a"));
assertEquals(0, VersionUtil.compareVersions(
"2.0.0-SNAPSHOT", "2.0.0-SNAPSHOT"));
assertEquals(0, VersionUtil.compareVersions("1", "1"));
assertEquals(0, VersionUtil.compareVersions("1", "1.0"));
assertEquals(0, VersionUtil.compareVersions("1", "1.0.0"));
assertEquals(0, VersionUtil.compareVersions("1.0", "1"));
assertEquals(0, VersionUtil.compareVersions("1.0", "1.0"));
assertEquals(0, VersionUtil.compareVersions("1.0", "1.0.0"));
assertEquals(0, VersionUtil.compareVersions("1.0.0", "1"));
assertEquals(0, VersionUtil.compareVersions("1.0.0", "1.0"));
assertEquals(0, VersionUtil.compareVersions("1.0.0", "1.0.0"));
assertEquals(0, VersionUtil.compareVersions("1.0.0-alpha-1", "1.0.0-a1"));
assertEquals(0, VersionUtil.compareVersions("1.0.0-alpha-2", "1.0.0-a2"));
assertEquals(0, VersionUtil.compareVersions("1.0.0-alpha1", "1.0.0-alpha-1"));
assertEquals(0, VersionUtil.compareVersions("1a0", "1.0.0-alpha-0"));
assertEquals(0, VersionUtil.compareVersions("1a0", "1-a0"));
assertEquals(0, VersionUtil.compareVersions("1.a0", "1-a0"));
assertEquals(0, VersionUtil.compareVersions("1.a0", "1.0.0-alpha-0"));
// Assert that lower versions are lower, and higher versions are higher.
assertExpectedValues("1", "2.0.0");
assertExpectedValues("1.0.0", "2");
assertExpectedValues("1.0.0", "2.0.0");
assertExpectedValues("1.0", "2.0.0");
assertExpectedValues("1.0.0", "2.0.0");
assertExpectedValues("1.0.0", "1.0.0a");
assertExpectedValues("1.0.0.0", "2.0.0");
assertExpectedValues("1.0.0", "1.0.0-dev");
assertExpectedValues("1.0.0", "1.0.1");
assertExpectedValues("1.0.0", "1.0.2");
assertExpectedValues("1.0.0", "1.1.0");
assertExpectedValues("2.0.0", "10.0.0");
assertExpectedValues("1.0.0", "1.0.0a");
assertExpectedValues("1.0.2a", "1.0.10");
assertExpectedValues("1.0.2a", "1.0.2b");
assertExpectedValues("1.0.2a", "1.0.2ab");
assertExpectedValues("1.0.0a1", "1.0.0a2");
assertExpectedValues("1.0.0a2", "1.0.0a10");
// The 'a' in "1.a" is not followed by digit, thus not treated as "alpha",
// and treated larger than "1.0", per maven's ComparableVersion class
// implementation.
assertExpectedValues("1.0", "1.a");
//The 'a' in "1.a0" is followed by digit, thus treated as "alpha-<digit>"
assertExpectedValues("1.a0", "1.0");
assertExpectedValues("1a0", "1.0");
assertExpectedValues("1.0.1-alpha-1", "1.0.1-alpha-2");
assertExpectedValues("1.0.1-beta-1", "1.0.1-beta-2");
// Snapshot builds precede their eventual releases.
assertExpectedValues("1.0-SNAPSHOT", "1.0");
assertExpectedValues("1.0.0-SNAPSHOT", "1.0");
assertExpectedValues("1.0.0-SNAPSHOT", "1.0.0");
assertExpectedValues("1.0.0", "1.0.1-SNAPSHOT");
assertExpectedValues("1.0.1-SNAPSHOT", "1.0.1");
assertExpectedValues("1.0.1-SNAPSHOT", "1.0.2");
assertExpectedValues("1.0.1-alpha-1", "1.0.1-SNAPSHOT");
assertExpectedValues("1.0.1-beta-1", "1.0.1-SNAPSHOT");
assertExpectedValues("1.0.1-beta-2", "1.0.1-SNAPSHOT");
}
private static void assertExpectedValues(String lower, String higher) {
assertTrue(VersionUtil.compareVersions(lower, higher) < 0);
assertTrue(VersionUtil.compareVersions(higher, lower) > 0);
}
}
| TestVersionUtil |
java | google__guava | android/guava/src/com/google/common/base/FinalizableReferenceQueue.java | {
"start": 10195,
"end": 10257
} | interface ____ {
/**
* Returns Finalizer. | FinalizerLoader |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ConstantPatternCompileTest.java | {
"start": 10403,
"end": 10970
} | class ____ {
/** This is a javadoc. * */
public static void myPopularStaticMethod() {
Matcher m = MY_PATTERN.matcher("aaaaab");
}
private static final Pattern MY_PATTERN = Pattern.compile("a+");
}
""")
.doTest();
}
@Test
public void fixGeneration_nonStaticInnerClass() {
testHelper
.addInputLines(
"in/Test.java",
"""
import java.util.regex.Matcher;
import java.util.regex.Pattern;
| Test |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/util/Chars.java | {
"start": 932,
"end": 2794
} | class ____ {
/** Carriage Return. */
public static final char CR = '\r';
/** Double Quote. */
public static final char DQUOTE = '\"';
/** Equals '='. */
public static final char EQ = '=';
/** Line Feed. */
public static final char LF = '\n';
/**
* NUL.
* @since 2.11.0
*/
public static final char NUL = 0;
/** Single Quote [']. */
public static final char QUOTE = '\'';
/** Space. */
public static final char SPACE = ' ';
/** Tab. */
public static final char TAB = '\t';
/**
* Converts a digit into an upper-case hexadecimal character or the null character if invalid.
*
* @param digit a number 0 - 15
* @return the hex character for that digit or '\0' if invalid
* @since 2.8.2
*/
public static char getUpperCaseHex(final int digit) {
if (digit < 0 || digit >= 16) {
return '\0';
}
return digit < 10 ? getNumericalDigit(digit) : getUpperCaseAlphaDigit(digit);
}
/**
* Converts a digit into an lower-case hexadecimal character or the null character if invalid.
*
* @param digit a number 0 - 15
* @return the hex character for that digit or '\0' if invalid
* @since 2.8.2
*/
public static char getLowerCaseHex(final int digit) {
if (digit < 0 || digit >= 16) {
return '\0';
}
return digit < 10 ? getNumericalDigit(digit) : getLowerCaseAlphaDigit(digit);
}
private static char getNumericalDigit(final int digit) {
return (char) ('0' + digit);
}
private static char getUpperCaseAlphaDigit(final int digit) {
return (char) ('A' + digit - 10);
}
private static char getLowerCaseAlphaDigit(final int digit) {
return (char) ('a' + digit - 10);
}
private Chars() {}
}
| Chars |
java | quarkusio__quarkus | extensions/security/runtime-spi/src/main/java/io/quarkus/security/spi/runtime/BlockingSecurityExecutor.java | {
"start": 568,
"end": 2446
} | interface ____ {
<T> Uni<T> executeBlocking(Supplier<? extends T> supplier);
static BlockingSecurityExecutor createBlockingExecutor(Supplier<Executor> executorSupplier) {
return new BlockingSecurityExecutor() {
@Override
public <T> Uni<T> executeBlocking(Supplier<? extends T> function) {
return Uni.createFrom().deferred(new Supplier<Uni<? extends T>>() {
@Override
public Uni<? extends T> get() {
if (BlockingOperationControl.isBlockingAllowed()) {
try {
return Uni.createFrom().item(function.get());
} catch (Throwable t) {
return Uni.createFrom().failure(t);
}
} else {
return Uni.createFrom().emitter(new Consumer<UniEmitter<? super T>>() {
@Override
public void accept(UniEmitter<? super T> uniEmitter) {
executorSupplier.get().execute(new Runnable() {
@Override
public void run() {
try {
uniEmitter.complete(function.get());
} catch (Throwable t) {
uniEmitter.fail(t);
}
}
});
}
});
}
}
});
}
};
}
}
| BlockingSecurityExecutor |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/support/DispatcherServletInitializerTests.java | {
"start": 4263,
"end": 4436
} | class ____ extends DispatcherServlet {
public MyDispatcherServlet(WebApplicationContext webApplicationContext) {
super(webApplicationContext);
}
}
}
| MyDispatcherServlet |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/stateless/fetching/Producer.java | {
"start": 352,
"end": 985
} | class ____ {
@Id
private Integer id;
private String name;
@OneToMany( mappedBy = "producer", fetch = FetchType.LAZY )
private Set<Product> products = new HashSet<>();
public Producer() {
}
public Producer(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Product> getProducts() {
return products;
}
public void setProducts(Set<Product> products) {
this.products = products;
}
}
| Producer |
java | quarkusio__quarkus | extensions/security/spi/src/main/java/io/quarkus/security/spi/RegisterClassSecurityCheckBuildItem.java | {
"start": 581,
"end": 1164
} | class ____ extends MultiBuildItem {
private final DotName className;
private final AnnotationInstance securityAnnotationInstance;
public RegisterClassSecurityCheckBuildItem(DotName className, AnnotationInstance securityAnnotationInstance) {
this.className = className;
this.securityAnnotationInstance = securityAnnotationInstance;
}
public DotName getClassName() {
return className;
}
public AnnotationInstance getSecurityAnnotationInstance() {
return securityAnnotationInstance;
}
}
| RegisterClassSecurityCheckBuildItem |
java | jhy__jsoup | src/main/java/org/jsoup/nodes/CDataNode.java | {
"start": 138,
"end": 841
} | class ____ extends TextNode {
public CDataNode(String text) {
super(text);
}
@Override
public String nodeName() {
return "#cdata";
}
/**
* Get the un-encoded, <b>non-normalized</b> text content of this CDataNode.
* @return un-encoded, non-normalized text
*/
@Override
public String text() {
return getWholeText();
}
@Override
void outerHtmlHead(QuietAppendable accum, Document.OutputSettings out) {
accum
.append("<![CDATA[")
.append(getWholeText())
.append("]]>");
}
@Override
public CDataNode clone() {
return (CDataNode) super.clone();
}
}
| CDataNode |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/sources/wmstrategies/WatermarkStrategy.java | {
"start": 1391,
"end": 2127
} | class ____ implements Serializable, Descriptor {
/**
* This method is a default implementation that uses java serialization and it is discouraged.
* All implementation should provide a more specific set of properties.
*/
@Override
public Map<String, String> toProperties() {
Map<String, String> properties = new HashMap<>();
properties.put(
Rowtime.ROWTIME_WATERMARKS_TYPE, Rowtime.ROWTIME_WATERMARKS_TYPE_VALUE_CUSTOM);
properties.put(Rowtime.ROWTIME_WATERMARKS_CLASS, this.getClass().getName());
properties.put(
Rowtime.ROWTIME_WATERMARKS_SERIALIZED, EncodingUtils.encodeObjectToString(this));
return properties;
}
}
| WatermarkStrategy |
java | spring-projects__spring-boot | module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfiguration.java | {
"start": 4621,
"end": 5483
} | class ____ extends EnumerablePropertySource<Object>
implements PropertySourceInfo {
private static final Map<String, String> PROPERTY_MAPPINGS = Map.of("local.management.port",
"local.server.port");
private static final String[] PROPERTY_NAMES = PROPERTY_MAPPINGS.keySet().toArray(String[]::new);
private final Environment environment;
LocalManagementPortPropertySource(Environment environment) {
super("Management Server");
this.environment = environment;
}
@Override
public String[] getPropertyNames() {
return PROPERTY_NAMES;
}
@Override
public @Nullable Object getProperty(String name) {
String mapped = PROPERTY_MAPPINGS.get(name);
return (mapped != null) ? this.environment.getProperty(mapped) : null;
}
@Override
public boolean isImmutable() {
return true;
}
}
}
| LocalManagementPortPropertySource |
java | apache__camel | components/camel-jgroups/src/main/java/org/apache/camel/component/jgroups/JGroupsConstants.java | {
"start": 900,
"end": 2406
} | class ____ {
@Metadata(description = "Address (`org.jgroups.Address`) of the channel associated with the\n" +
"endpoint.",
javaType = "org.jgroups.Address")
public static final String HEADER_JGROUPS_CHANNEL_ADDRESS = "JGROUPS_CHANNEL_ADDRESS";
@Metadata(description = "*Consumer*: The `org.jgroups.Address` instance extracted by\n" +
"`org.jgroups.Message`.getDest() method of the consumed message.\n" +
"*Producer*: The custom destination `org.jgroups.Address` of the message to be sent.",
javaType = "org.jgroups.Address")
public static final String HEADER_JGROUPS_DEST = "JGROUPS_DEST";
@Metadata(description = "*Consumer* : The `org.jgroups.Address` instance extracted by\n" +
"`org.jgroups.Message`.getSrc() method of the consumed message. \n" +
"*Producer*: The custom source `org.jgroups.Address` of the message to be sent.",
javaType = "org.jgroups.Address")
public static final String HEADER_JGROUPS_SRC = "JGROUPS_SRC";
@Metadata(description = "The original `org.jgroups.Message` instance from which the body of the\n" +
"consumed message has been extracted.",
javaType = "org.jgroups.Message")
public static final String HEADER_JGROUPS_ORIGINAL_MESSAGE = "JGROUPS_ORIGINAL_MESSAGE";
private JGroupsConstants() {
}
}
| JGroupsConstants |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/FunctionalInterfaceClashTest.java | {
"start": 12695,
"end": 13287
} | class ____ extends Super {
void barr(Function<String, Integer> f) {}
void barr(Consumer<String> c) {}
// BUG: Diagnostic contains: When passing lambda arguments to this function
void foo(Function<Integer, Integer> f) {}
void foo(Consumer<Integer> c) {}
}
""")
.doTest();
}
@Test
public void oneIsMoreSpecific_notAmbiguous() {
testHelper
.addSourceLines(
"Test.java",
"""
import java.util.function.Consumer;
public | BaseClass |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/index/ExecutableIndexAction.java | {
"start": 1812,
"end": 12218
} | class ____ extends ExecutableAction<IndexAction> {
private static final String INDEX_FIELD = "_index";
private static final String TYPE_FIELD = "_type";
private static final String ID_FIELD = "_id";
private final Client client;
private final TimeValue indexDefaultTimeout;
private final TimeValue bulkDefaultTimeout;
public ExecutableIndexAction(
IndexAction action,
Logger logger,
Client client,
TimeValue indexDefaultTimeout,
TimeValue bulkDefaultTimeout
) {
super(action, logger);
this.client = client;
this.indexDefaultTimeout = action.timeout != null ? action.timeout : indexDefaultTimeout;
this.bulkDefaultTimeout = action.timeout != null ? action.timeout : bulkDefaultTimeout;
}
@SuppressWarnings("unchecked")
@Override
public Action.Result execute(String actionId, WatchExecutionContext ctx, Payload payload) throws Exception {
Map<String, Object> data = payload.data();
if (data.containsKey("_doc")) {
Object doc = data.get("_doc");
if (doc instanceof Iterable) {
return indexBulk((Iterable<?>) doc, actionId, ctx);
}
if (doc.getClass().isArray()) {
return indexBulk(new ArrayObjectIterator.Iterable(doc), actionId, ctx);
}
if (doc instanceof Map) {
data = (Map<String, Object>) doc;
} else {
throw illegalState(
"could not execute action [{}] of watch [{}]. failed to index payload data."
+ "[_data] field must either hold a Map or an List/Array of Maps",
actionId,
ctx.watch().id()
);
}
}
if (data.containsKey(INDEX_FIELD) || data.containsKey(TYPE_FIELD) || data.containsKey(ID_FIELD)) {
data = mutableMap(data);
}
IndexRequest indexRequest = new IndexRequest();
if (action.refreshPolicy != null) {
indexRequest.setRefreshPolicy(action.refreshPolicy);
}
indexRequest.index(getField(actionId, ctx.id().watchId(), "index", data, INDEX_FIELD, action.index));
indexRequest.id(getField(actionId, ctx.id().watchId(), "id", data, ID_FIELD, action.docId));
if (action.opType != null) {
indexRequest.opType(action.opType);
}
data = addTimestampToDocument(data, ctx.executionTime());
BytesReference bytesReference;
try (XContentBuilder builder = jsonBuilder()) {
indexRequest.source(builder.prettyPrint().map(data));
}
if (ctx.simulateAction(actionId)) {
return new IndexAction.Simulated(
indexRequest.index(),
indexRequest.id(),
action.refreshPolicy,
new XContentSource(indexRequest.source(), XContentType.JSON)
);
}
ClientHelper.assertNoAuthorizationHeader(ctx.watch().status().getHeaders());
DocWriteResponse response = ClientHelper.executeWithHeaders(
ctx.watch().status().getHeaders(),
ClientHelper.WATCHER_ORIGIN,
client,
() -> client.index(indexRequest).actionGet(indexDefaultTimeout)
);
try (XContentBuilder builder = jsonBuilder()) {
indexResponseToXContent(builder, response);
bytesReference = BytesReference.bytes(builder);
}
return new IndexAction.Result(Status.SUCCESS, new XContentSource(bytesReference, XContentType.JSON));
}
Action.Result indexBulk(Iterable<?> list, String actionId, WatchExecutionContext ctx) throws Exception {
if (action.docId != null) {
throw illegalState("could not execute action [{}] of watch [{}]. [doc_id] cannot be used with bulk [_doc] indexing");
}
BulkRequest bulkRequest = new BulkRequest();
if (action.refreshPolicy != null) {
bulkRequest.setRefreshPolicy(action.refreshPolicy);
}
for (Object item : list) {
if ((item instanceof Map) == false) {
throw illegalState(
"could not execute action [{}] of watch [{}]. failed to index payload data. "
+ "[_data] field must either hold a Map or an List/Array of Maps",
actionId,
ctx.watch().id()
);
}
@SuppressWarnings("unchecked")
Map<String, Object> doc = (Map<String, Object>) item;
if (doc.containsKey(INDEX_FIELD) || doc.containsKey(TYPE_FIELD) || doc.containsKey(ID_FIELD)) {
doc = mutableMap(doc);
}
IndexRequest indexRequest = new IndexRequest();
indexRequest.index(getField(actionId, ctx.id().watchId(), "index", doc, INDEX_FIELD, action.index));
indexRequest.id(getField(actionId, ctx.id().watchId(), "id", doc, ID_FIELD, action.docId));
if (action.opType != null) {
indexRequest.opType(action.opType);
}
doc = addTimestampToDocument(doc, ctx.executionTime());
try (XContentBuilder builder = jsonBuilder()) {
indexRequest.source(builder.prettyPrint().map(doc));
}
bulkRequest.add(indexRequest);
}
if (ctx.simulateAction(actionId)) {
try (XContentBuilder builder = jsonBuilder().startArray()) {
for (DocWriteRequest<?> request : bulkRequest.requests()) {
builder.startObject();
builder.field("_id", request.id());
builder.field("_index", request.index());
builder.endObject();
}
builder.endArray();
return new IndexAction.Simulated(
"",
"",
action.refreshPolicy,
new XContentSource(BytesReference.bytes(builder), XContentType.JSON)
);
}
}
ClientHelper.assertNoAuthorizationHeader(ctx.watch().status().getHeaders());
BulkResponse bulkResponse = ClientHelper.executeWithHeaders(
ctx.watch().status().getHeaders(),
ClientHelper.WATCHER_ORIGIN,
client,
() -> client.bulk(bulkRequest).actionGet(bulkDefaultTimeout)
);
try (XContentBuilder jsonBuilder = jsonBuilder().startArray()) {
for (BulkItemResponse item : bulkResponse) {
itemResponseToXContent(jsonBuilder, item);
}
jsonBuilder.endArray();
// different error states, depending on how successful the bulk operation was
long failures = Stream.of(bulkResponse.getItems()).filter(BulkItemResponse::isFailed).count();
if (failures == 0) {
return new IndexAction.Result(Status.SUCCESS, new XContentSource(BytesReference.bytes(jsonBuilder), XContentType.JSON));
} else if (failures == bulkResponse.getItems().length) {
return new IndexAction.Result(Status.FAILURE, new XContentSource(BytesReference.bytes(jsonBuilder), XContentType.JSON));
} else {
return new IndexAction.Result(
Status.PARTIAL_FAILURE,
new XContentSource(BytesReference.bytes(jsonBuilder), XContentType.JSON)
);
}
}
}
private Map<String, Object> addTimestampToDocument(Map<String, Object> data, ZonedDateTime executionTime) {
if (action.executionTimeField != null) {
data = mutableMap(data);
data.put(action.executionTimeField, WatcherDateTimeUtils.formatDate(executionTime));
}
return data;
}
/**
* Extracts the specified field out of data map, or alternative falls back to the action value
*/
private static String getField(
String actionId,
String watchId,
String name,
Map<String, Object> data,
String fieldName,
String defaultValue
) {
Object obj;
// map may be immutable - only try to remove if it's actually there
if (data.containsKey(fieldName) && (obj = data.remove(fieldName)) != null) {
if (defaultValue != null) {
throw illegalState(
"could not execute action [{}] of watch [{}]. "
+ "[ctx.payload.{}] or [ctx.payload._doc.{}] were set together with action [{}] field. Only set one of them",
actionId,
watchId,
fieldName,
fieldName,
name
);
} else {
return obj.toString();
}
}
return defaultValue;
}
/**
* Guarantees that the {@code data} is mutable for any code that needs to modify the {@linkplain Map} before using it (e.g., from
* singleton, immutable {@code Map}s).
*
* @param data The map to make mutable
* @return Always a {@linkplain HashMap}
*/
private static Map<String, Object> mutableMap(Map<String, Object> data) {
return data instanceof HashMap ? data : new HashMap<>(data);
}
private static void itemResponseToXContent(XContentBuilder builder, BulkItemResponse item) throws IOException {
if (item.isFailed()) {
builder.startObject()
.field("failed", item.isFailed())
.field("message", item.getFailureMessage())
.field("id", item.getId())
.field("index", item.getIndex())
.endObject();
} else {
indexResponseToXContent(builder, item.getResponse());
}
}
static void indexResponseToXContent(XContentBuilder builder, DocWriteResponse response) throws IOException {
builder.startObject()
.field("created", response.getResult() == DocWriteResponse.Result.CREATED)
.field("result", response.getResult().getLowercase())
.field("id", response.getId())
.field("version", response.getVersion())
.field("index", response.getIndex())
.endObject();
}
}
| ExecutableIndexAction |
java | netty__netty | codec-compression/src/test/java/io/netty/handler/codec/compression/BrotliDecoderTest.java | {
"start": 1348,
"end": 5795
} | class ____ {
private static Random RANDOM;
private static final byte[] BYTES_SMALL = new byte[256];
private static final byte[] BYTES_LARGE = new byte[256 * 1024];
private static byte[] COMPRESSED_BYTES_SMALL;
private static byte[] COMPRESSED_BYTES_LARGE;
@BeforeAll
static void setUp() {
try {
Brotli.ensureAvailability();
RANDOM = new Random();
fillArrayWithCompressibleData(BYTES_SMALL);
fillArrayWithCompressibleData(BYTES_LARGE);
COMPRESSED_BYTES_SMALL = compress(BYTES_SMALL);
COMPRESSED_BYTES_LARGE = compress(BYTES_LARGE);
} catch (Throwable throwable) {
throw new ExceptionInInitializerError(throwable);
}
}
private static final ByteBuf WRAPPED_BYTES_SMALL = Unpooled.unreleasableBuffer(
Unpooled.wrappedBuffer(BYTES_SMALL)).asReadOnly();
private static final ByteBuf WRAPPED_BYTES_LARGE = Unpooled.unreleasableBuffer(
Unpooled.wrappedBuffer(BYTES_LARGE)).asReadOnly();
private static void fillArrayWithCompressibleData(byte[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = i % 4 != 0 ? 0 : (byte) RANDOM.nextInt();
}
}
private static byte[] compress(byte[] data) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
BrotliOutputStream brotliOs = new BrotliOutputStream(os);
brotliOs.write(data);
brotliOs.close();
return os.toByteArray();
}
private EmbeddedChannel channel;
@BeforeEach
public void initChannel() {
channel = new EmbeddedChannel(new BrotliDecoder());
}
@AfterEach
public void destroyChannel() {
if (channel != null) {
channel.finishAndReleaseAll();
channel = null;
}
}
public static ByteBuf[] smallData() {
ByteBuf heap = Unpooled.wrappedBuffer(COMPRESSED_BYTES_SMALL);
ByteBuf direct = Unpooled.directBuffer(COMPRESSED_BYTES_SMALL.length);
direct.writeBytes(COMPRESSED_BYTES_SMALL);
return new ByteBuf[]{heap, direct};
}
public static ByteBuf[] largeData() {
ByteBuf heap = Unpooled.wrappedBuffer(COMPRESSED_BYTES_LARGE);
ByteBuf direct = Unpooled.directBuffer(COMPRESSED_BYTES_LARGE.length);
direct.writeBytes(COMPRESSED_BYTES_LARGE);
return new ByteBuf[]{heap, direct};
}
@ParameterizedTest
@MethodSource("smallData")
public void testDecompressionOfSmallChunkOfData(ByteBuf data) {
testDecompression(WRAPPED_BYTES_SMALL.duplicate(), data);
}
@ParameterizedTest
@MethodSource("largeData")
public void testDecompressionOfLargeChunkOfData(ByteBuf data) {
testDecompression(WRAPPED_BYTES_LARGE.duplicate(), data);
}
@ParameterizedTest
@MethodSource("largeData")
public void testDecompressionOfBatchedFlowOfData(ByteBuf data) {
testDecompressionOfBatchedFlow(WRAPPED_BYTES_LARGE, data);
}
private void testDecompression(final ByteBuf expected, final ByteBuf data) {
assertTrue(channel.writeInbound(data));
ByteBuf decompressed = readDecompressed(channel);
assertEquals(expected, decompressed);
decompressed.release();
}
private void testDecompressionOfBatchedFlow(final ByteBuf expected, final ByteBuf data) {
final int compressedLength = data.readableBytes();
int written = 0, length = RANDOM.nextInt(100);
while (written + length < compressedLength) {
ByteBuf compressedBuf = data.retainedSlice(written, length);
channel.writeInbound(compressedBuf);
written += length;
length = RANDOM.nextInt(100);
}
ByteBuf compressedBuf = data.slice(written, compressedLength - written);
assertTrue(channel.writeInbound(compressedBuf.retain()));
ByteBuf decompressedBuf = readDecompressed(channel);
assertEquals(expected, decompressedBuf);
decompressedBuf.release();
data.release();
}
private static ByteBuf readDecompressed(final EmbeddedChannel channel) {
CompositeByteBuf decompressed = Unpooled.compositeBuffer();
ByteBuf msg;
while ((msg = channel.readInbound()) != null) {
decompressed.addComponent(true, msg);
}
return decompressed;
}
}
| BrotliDecoderTest |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestSlowDiskTracker.java | {
"start": 2721,
"end": 18507
} | class ____ {
public static final Logger LOG = LoggerFactory.getLogger(
TestSlowDiskTracker.class);
private static Configuration conf;
private SlowDiskTracker tracker;
private FakeTimer timer;
private long reportValidityMs;
private static final long OUTLIERS_REPORT_INTERVAL = 1000;
private static final ObjectReader READER = new ObjectMapper().readerFor(
new TypeReference<ArrayList<DiskLatency>>() {});
static {
conf = new HdfsConfiguration();
conf.setLong(DFS_HEARTBEAT_INTERVAL_KEY, 1L);
conf.setInt(DFS_DATANODE_FILEIO_PROFILING_SAMPLING_PERCENTAGE_KEY, 100);
conf.setTimeDuration(DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_KEY,
OUTLIERS_REPORT_INTERVAL, TimeUnit.MILLISECONDS);
}
@BeforeEach
public void setup() {
timer = new FakeTimer();
tracker = new SlowDiskTracker(conf, timer);
reportValidityMs = tracker.getReportValidityMs();
}
@Test
public void testDataNodeHeartbeatSlowDiskReport() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2)
.build();
try {
DataNode dn1 = cluster.getDataNodes().get(0);
DataNode dn2 = cluster.getDataNodes().get(1);
NameNode nn = cluster.getNameNode(0);
DatanodeManager datanodeManager = nn.getNamesystem().getBlockManager()
.getDatanodeManager();
SlowDiskTracker slowDiskTracker = datanodeManager.getSlowDiskTracker();
slowDiskTracker.setReportValidityMs(OUTLIERS_REPORT_INTERVAL * 100);
dn1.getDiskMetrics().addSlowDiskForTesting("disk1", ImmutableMap.of(
DiskOp.WRITE, 1.3));
dn1.getDiskMetrics().addSlowDiskForTesting("disk2", ImmutableMap.of(
DiskOp.READ, 1.6, DiskOp.WRITE, 1.1));
dn2.getDiskMetrics().addSlowDiskForTesting("disk1", ImmutableMap.of(
DiskOp.METADATA, 0.8));
dn2.getDiskMetrics().addSlowDiskForTesting("disk2", ImmutableMap.of(
DiskOp.WRITE, 1.3));
String dn1ID = dn1.getDatanodeId().getIpcAddr(false);
String dn2ID = dn2.getDatanodeId().getIpcAddr(false);
// Advance the timer and wait for NN to receive reports from DataNodes.
Thread.sleep(OUTLIERS_REPORT_INTERVAL);
// Wait for NN to receive reports from all DNs
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return (slowDiskTracker.getSlowDisksReport().size() == 4);
}
}, 1000, 100000);
Map<String, DiskLatency> slowDisksReport = getSlowDisksReportForTesting(
slowDiskTracker);
assertThat(slowDisksReport.size()).isEqualTo(4);
assertTrue(Math.abs(slowDisksReport.get(dn1ID + ":disk1")
.getLatency(DiskOp.WRITE) - 1.3) < 0.0000001);
assertTrue(Math.abs(slowDisksReport.get(dn1ID + ":disk2")
.getLatency(DiskOp.READ) - 1.6) < 0.0000001);
assertTrue(Math.abs(slowDisksReport.get(dn1ID + ":disk2")
.getLatency(DiskOp.WRITE) - 1.1) < 0.0000001);
assertTrue(Math.abs(slowDisksReport.get(dn2ID + ":disk1")
.getLatency(DiskOp.METADATA) - 0.8) < 0.0000001);
assertTrue(Math.abs(slowDisksReport.get(dn2ID + ":disk2")
.getLatency(DiskOp.WRITE) - 1.3) < 0.0000001);
// Test the slow disk report JSON string
ArrayList<DiskLatency> jsonReport = getAndDeserializeJson(
slowDiskTracker.getSlowDiskReportAsJsonString());
assertThat(jsonReport.size()).isEqualTo(4);
assertTrue(isDiskInReports(jsonReport, dn1ID, "disk1", DiskOp.WRITE, 1.3));
assertTrue(isDiskInReports(jsonReport, dn1ID, "disk2", DiskOp.READ, 1.6));
assertTrue(isDiskInReports(jsonReport, dn1ID, "disk2", DiskOp.WRITE, 1.1));
assertTrue(isDiskInReports(jsonReport, dn2ID, "disk1", DiskOp.METADATA,
0.8));
assertTrue(isDiskInReports(jsonReport, dn2ID, "disk2", DiskOp.WRITE, 1.3));
} finally {
cluster.shutdown();
}
}
/**
* Edge case, there are no reports to retrieve.
*/
@Test
public void testEmptyReports() {
tracker.updateSlowDiskReportAsync(timer.monotonicNow());
assertTrue(getSlowDisksReportForTesting(tracker).isEmpty());
}
@Test
public void testReportsAreRetrieved() throws Exception {
addSlowDiskForTesting("dn1", "disk1",
ImmutableMap.of(DiskOp.METADATA, 1.1, DiskOp.READ, 1.8));
addSlowDiskForTesting("dn1", "disk2",
ImmutableMap.of(DiskOp.READ, 1.3));
addSlowDiskForTesting("dn2", "disk2",
ImmutableMap.of(DiskOp.READ, 1.1));
tracker.updateSlowDiskReportAsync(timer.monotonicNow());
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return !tracker.getSlowDisksReport().isEmpty();
}
}, 500, 5000);
Map<String, DiskLatency> reports = getSlowDisksReportForTesting(tracker);
assertThat(reports.size()).isEqualTo(3);
assertTrue(Math.abs(reports.get("dn1:disk1")
.getLatency(DiskOp.METADATA) - 1.1) < 0.0000001);
assertTrue(Math.abs(reports.get("dn1:disk1")
.getLatency(DiskOp.READ) - 1.8) < 0.0000001);
assertTrue(Math.abs(reports.get("dn1:disk2")
.getLatency(DiskOp.READ) - 1.3) < 0.0000001);
assertTrue(Math.abs(reports.get("dn2:disk2")
.getLatency(DiskOp.READ) - 1.1) < 0.0000001);
}
/**
* Test that when all reports are expired, we get back nothing.
*/
@Test
public void testAllReportsAreExpired() throws Exception {
addSlowDiskForTesting("dn1", "disk1",
ImmutableMap.of(DiskOp.METADATA, 1.1, DiskOp.READ, 1.8));
addSlowDiskForTesting("dn1", "disk2",
ImmutableMap.of(DiskOp.READ, 1.3));
addSlowDiskForTesting("dn2", "disk2",
ImmutableMap.of(DiskOp.WRITE, 1.1));
// No reports should expire after 1ms.
timer.advance(1);
tracker.updateSlowDiskReportAsync(timer.monotonicNow());
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return !tracker.getSlowDisksReport().isEmpty();
}
}, 500, 5000);
Map<String, DiskLatency> reports = getSlowDisksReportForTesting(tracker);
assertThat(reports.size()).isEqualTo(3);
assertTrue(Math.abs(reports.get("dn1:disk1")
.getLatency(DiskOp.METADATA) - 1.1) < 0.0000001);
assertTrue(Math.abs(reports.get("dn1:disk1")
.getLatency(DiskOp.READ) - 1.8) < 0.0000001);
assertTrue(Math.abs(reports.get("dn1:disk2")
.getLatency(DiskOp.READ) - 1.3) < 0.0000001);
assertTrue(Math.abs(reports.get("dn2:disk2")
.getLatency(DiskOp.WRITE) - 1.1) < 0.0000001);
// All reports should expire after REPORT_VALIDITY_MS.
timer.advance(reportValidityMs);
tracker.updateSlowDiskReportAsync(timer.monotonicNow());
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return tracker.getSlowDisksReport().isEmpty();
}
}, 500, 3000);
reports = getSlowDisksReportForTesting(tracker);
assertThat(reports.size()).isEqualTo(0);
}
/**
* Test the case when a subset of reports has expired.
* Ensure that we only get back non-expired reports.
*/
@Test
public void testSomeReportsAreExpired() throws Exception {
addSlowDiskForTesting("dn1", "disk1",
ImmutableMap.of(DiskOp.METADATA, 1.1, DiskOp.READ, 1.8));
addSlowDiskForTesting("dn1", "disk2",
ImmutableMap.of(DiskOp.READ, 1.3));
timer.advance(reportValidityMs);
addSlowDiskForTesting("dn2", "disk2",
ImmutableMap.of(DiskOp.WRITE, 1.1));
tracker.updateSlowDiskReportAsync(timer.monotonicNow());
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return !tracker.getSlowDisksReport().isEmpty();
}
}, 500, 5000);
Map<String, DiskLatency> reports = getSlowDisksReportForTesting(tracker);
assertThat(reports.size()).isEqualTo(1);
assertTrue(Math.abs(reports.get("dn2:disk2")
.getLatency(DiskOp.WRITE) - 1.1) < 0.0000001);
}
/**
* Test the case when an expired report is replaced by a valid one.
*/
@Test
public void testReplacement() throws Exception {
addSlowDiskForTesting("dn1", "disk1",
ImmutableMap.of(DiskOp.METADATA, 1.1, DiskOp.READ, 1.8));
timer.advance(reportValidityMs);
addSlowDiskForTesting("dn1", "disk1",
ImmutableMap.of(DiskOp.READ, 1.4));
tracker.updateSlowDiskReportAsync(timer.monotonicNow());
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return !tracker.getSlowDisksReport().isEmpty();
}
}, 500, 5000);
Map<String, DiskLatency> reports = getSlowDisksReportForTesting(tracker);
assertThat(reports.size()).isEqualTo(1);
assertTrue(reports.get("dn1:disk1").getLatency(DiskOp.METADATA) == null);
assertTrue(Math.abs(reports.get("dn1:disk1")
.getLatency(DiskOp.READ) - 1.4) < 0.0000001);
}
@Test
public void testGetJson() throws Exception {
addSlowDiskForTesting("dn1", "disk1",
ImmutableMap.of(DiskOp.METADATA, 1.1, DiskOp.READ, 1.8));
addSlowDiskForTesting("dn1", "disk2",
ImmutableMap.of(DiskOp.READ, 1.3));
addSlowDiskForTesting("dn2", "disk2",
ImmutableMap.of(DiskOp.WRITE, 1.1));
addSlowDiskForTesting("dn3", "disk1",
ImmutableMap.of(DiskOp.WRITE, 1.1));
tracker.updateSlowDiskReportAsync(timer.monotonicNow());
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return tracker.getSlowDiskReportAsJsonString() != null;
}
}, 500, 5000);
ArrayList<DiskLatency> jsonReport = getAndDeserializeJson(
tracker.getSlowDiskReportAsJsonString());
// And ensure its contents are what we expect.
assertThat(jsonReport.size()).isEqualTo(4);
assertTrue(isDiskInReports(jsonReport, "dn1", "disk1", DiskOp.METADATA,
1.1));
assertTrue(isDiskInReports(jsonReport, "dn1", "disk1", DiskOp.READ, 1.8));
assertTrue(isDiskInReports(jsonReport, "dn1", "disk2", DiskOp.READ, 1.3));
assertTrue(isDiskInReports(jsonReport, "dn2", "disk2", DiskOp.WRITE, 1.1));
assertTrue(isDiskInReports(jsonReport, "dn3", "disk1", DiskOp.WRITE, 1.1));
}
@Test
public void testGetJsonSizeIsLimited() throws Exception {
addSlowDiskForTesting("dn1", "disk1",
ImmutableMap.of(DiskOp.READ, 1.1));
addSlowDiskForTesting("dn1", "disk2",
ImmutableMap.of(DiskOp.READ, 1.2));
addSlowDiskForTesting("dn1", "disk3",
ImmutableMap.of(DiskOp.READ, 1.3));
addSlowDiskForTesting("dn2", "disk1",
ImmutableMap.of(DiskOp.READ, 1.4));
addSlowDiskForTesting("dn2", "disk2",
ImmutableMap.of(DiskOp.READ, 1.5));
addSlowDiskForTesting("dn3", "disk1",
ImmutableMap.of(DiskOp.WRITE, 1.6));
addSlowDiskForTesting("dn3", "disk2",
ImmutableMap.of(DiskOp.READ, 1.7));
addSlowDiskForTesting("dn3", "disk3",
ImmutableMap.of(DiskOp.READ, 1.2));
tracker.updateSlowDiskReportAsync(timer.monotonicNow());
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return tracker.getSlowDiskReportAsJsonString() != null;
}
}, 500, 5000);
ArrayList<DiskLatency> jsonReport = getAndDeserializeJson(
tracker.getSlowDiskReportAsJsonString());
// Ensure that only the top 5 highest latencies are in the report.
assertThat(jsonReport.size()).isEqualTo(5);
assertTrue(isDiskInReports(jsonReport, "dn3", "disk2", DiskOp.READ, 1.7));
assertTrue(isDiskInReports(jsonReport, "dn3", "disk1", DiskOp.WRITE, 1.6));
assertTrue(isDiskInReports(jsonReport, "dn2", "disk2", DiskOp.READ, 1.5));
assertTrue(isDiskInReports(jsonReport, "dn2", "disk1", DiskOp.READ, 1.4));
assertTrue(isDiskInReports(jsonReport, "dn1", "disk3", DiskOp.READ, 1.3));
// Remaining nodes should be in the list.
assertFalse(isDiskInReports(jsonReport, "dn1", "disk1", DiskOp.READ, 1.1));
assertFalse(isDiskInReports(jsonReport, "dn1", "disk2", DiskOp.READ, 1.2));
assertFalse(isDiskInReports(jsonReport, "dn3", "disk3", DiskOp.READ, 1.2));
}
@Test
public void testEmptyReport() throws Exception {
addSlowDiskForTesting("dn1", "disk1",
ImmutableMap.of(DiskOp.READ, 1.1));
timer.advance(reportValidityMs);
tracker.updateSlowDiskReportAsync(timer.monotonicNow());
Thread.sleep(OUTLIERS_REPORT_INTERVAL*2);
assertTrue(tracker.getSlowDiskReportAsJsonString() == null);
}
@Test
public void testRemoveInvalidReport() throws Exception {
MiniDFSCluster cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
NameNode nn = cluster.getNameNode(0);
DatanodeManager datanodeManager =
nn.getNamesystem().getBlockManager().getDatanodeManager();
SlowDiskTracker slowDiskTracker = datanodeManager.getSlowDiskTracker();
slowDiskTracker.setReportValidityMs(OUTLIERS_REPORT_INTERVAL * 3);
assertTrue(slowDiskTracker.getSlowDisksReport().isEmpty());
slowDiskTracker.addSlowDiskReport(
"dn1",
generateSlowDiskReport("disk1",
Collections.singletonMap(DiskOp.WRITE, 1.3)));
slowDiskTracker.addSlowDiskReport(
"dn2",
generateSlowDiskReport("disk2",
Collections.singletonMap(DiskOp.WRITE, 1.1)));
// wait for slow disk report
GenericTestUtils.waitFor(() -> !slowDiskTracker.getSlowDisksReport()
.isEmpty(), 500, 5000);
Map<String, DiskLatency> slowDisksReport =
getSlowDisksReportForTesting(slowDiskTracker);
assertEquals(2, slowDisksReport.size());
// wait for invalid report to be removed
Thread.sleep(OUTLIERS_REPORT_INTERVAL * 3);
GenericTestUtils.waitFor(() -> slowDiskTracker.getSlowDisksReport()
.isEmpty(), 500, 5000);
slowDisksReport = getSlowDisksReportForTesting(slowDiskTracker);
assertEquals(0, slowDisksReport.size());
} finally {
cluster.shutdown();
}
}
private boolean isDiskInReports(ArrayList<DiskLatency> reports,
String dataNodeID, String disk, DiskOp diskOp, double latency) {
String diskID = SlowDiskTracker.getSlowDiskIDForReport(dataNodeID, disk);
for (DiskLatency diskLatency : reports) {
if (diskLatency.getSlowDiskID().equals(diskID)) {
if (diskLatency.getLatency(diskOp) == null) {
return false;
}
if (Math.abs(diskLatency.getLatency(diskOp) - latency) < 0.0000001) {
return true;
}
}
}
return false;
}
private ArrayList<DiskLatency> getAndDeserializeJson(
final String json) throws IOException {
return READER.readValue(json);
}
private void addSlowDiskForTesting(String dnID, String disk,
Map<DiskOp, Double> latencies) {
Map<String, Map<DiskOp, Double>> slowDisk = Maps.newHashMap();
slowDisk.put(disk, latencies);
SlowDiskReports slowDiskReport = SlowDiskReports.create(slowDisk);
tracker.addSlowDiskReport(dnID, slowDiskReport);
}
private SlowDiskReports generateSlowDiskReport(String disk,
Map<DiskOp, Double> latencies) {
Map<String, Map<DiskOp, Double>> slowDisk = Maps.newHashMap();
slowDisk.put(disk, latencies);
SlowDiskReports slowDiskReport = SlowDiskReports.create(slowDisk);
return slowDiskReport;
}
Map<String, DiskLatency> getSlowDisksReportForTesting(
SlowDiskTracker slowDiskTracker) {
Map<String, DiskLatency> slowDisksMap = Maps.newHashMap();
for (DiskLatency diskLatency : slowDiskTracker.getSlowDisksReport()) {
slowDisksMap.put(diskLatency.getSlowDiskID(), diskLatency);
}
return slowDisksMap;
}
}
| TestSlowDiskTracker |
java | grpc__grpc-java | netty/src/jmh/java/io/grpc/netty/InboundHeadersBenchmark.java | {
"start": 1533,
"end": 6907
} | class ____ {
private static AsciiString[] requestHeaders;
private static AsciiString[] responseHeaders;
static {
setupRequestHeaders();
setupResponseHeaders();
}
// Headers taken from the gRPC spec.
private static void setupRequestHeaders() {
requestHeaders = new AsciiString[18];
int i = 0;
requestHeaders[i++] = AsciiString.of(":method");
requestHeaders[i++] = AsciiString.of("POST");
requestHeaders[i++] = AsciiString.of(":scheme");
requestHeaders[i++] = AsciiString.of("http");
requestHeaders[i++] = AsciiString.of(":path");
requestHeaders[i++] = AsciiString.of("/google.pubsub.v2.PublisherService/CreateTopic");
requestHeaders[i++] = AsciiString.of(":authority");
requestHeaders[i++] = AsciiString.of("pubsub.googleapis.com");
requestHeaders[i++] = AsciiString.of("te");
requestHeaders[i++] = AsciiString.of("trailers");
requestHeaders[i++] = AsciiString.of("grpc-timeout");
requestHeaders[i++] = AsciiString.of("1S");
requestHeaders[i++] = AsciiString.of("content-type");
requestHeaders[i++] = AsciiString.of("application/grpc+proto");
requestHeaders[i++] = AsciiString.of("grpc-encoding");
requestHeaders[i++] = AsciiString.of("gzip");
requestHeaders[i++] = AsciiString.of("authorization");
requestHeaders[i] = AsciiString.of("Bearer y235.wef315yfh138vh31hv93hv8h3v");
}
private static void setupResponseHeaders() {
responseHeaders = new AsciiString[4];
int i = 0;
responseHeaders[i++] = AsciiString.of(":status");
responseHeaders[i++] = AsciiString.of("200");
responseHeaders[i++] = AsciiString.of("grpc-encoding");
responseHeaders[i] = AsciiString.of("gzip");
}
/**
* Checkstyle.
*/
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void grpcHeaders_serverHandler(Blackhole bh) {
serverHandler(bh, new GrpcHttp2RequestHeaders(4));
}
/**
* Checkstyle.
*/
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void defaultHeaders_serverHandler(Blackhole bh) {
serverHandler(bh, new DefaultHttp2Headers(true, 9));
}
/**
* Checkstyle.
*/
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void grpcHeaders_clientHandler(Blackhole bh) {
clientHandler(bh, new GrpcHttp2ResponseHeaders(2));
}
/**
* Checkstyle.
*/
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void defaultHeaders_clientHandler(Blackhole bh) {
clientHandler(bh, new DefaultHttp2Headers(true, 2));
}
@CompilerControl(CompilerControl.Mode.INLINE)
private static void serverHandler(Blackhole bh, Http2Headers headers) {
for (int i = 0; i < requestHeaders.length; i += 2) {
bh.consume(headers.add(requestHeaders[i], requestHeaders[i + 1]));
}
// Sequence of headers accessed in NettyServerHandler
bh.consume(headers.get(TE_TRAILERS));
bh.consume(headers.get(CONTENT_TYPE_HEADER));
bh.consume(headers.method());
bh.consume(headers.get(CONTENT_TYPE_HEADER));
bh.consume(headers.path());
bh.consume(Utils.convertHeaders(headers));
}
@CompilerControl(CompilerControl.Mode.INLINE)
private static void clientHandler(Blackhole bh, Http2Headers headers) {
// NettyClientHandler does not directly access headers, but convert to Metadata immediately.
bh.consume(headers.add(responseHeaders[0], responseHeaders[1]));
bh.consume(headers.add(responseHeaders[2], responseHeaders[3]));
bh.consume(Utils.convertHeaders(headers));
}
///**
// * Prints the size of the header objects in bytes. Needs JOL (Java Object Layout) as a
// * dependency.
// */
//public static void main(String... args) {
// Http2Headers grpcRequestHeaders = new GrpcHttp2RequestHeaders(4);
// Http2Headers defaultRequestHeaders = new DefaultHttp2Headers(true, 9);
// for (int i = 0; i < requestHeaders.length; i += 2) {
// grpcRequestHeaders.add(requestHeaders[i], requestHeaders[i + 1]);
// defaultRequestHeaders.add(requestHeaders[i], requestHeaders[i + 1]);
// }
// long c = 10L;
// int m = ((int) c) / 20;
// long grpcRequestHeadersBytes = GraphLayout.parseInstance(grpcRequestHeaders).totalSize();
// long defaultRequestHeadersBytes =
// GraphLayout.parseInstance(defaultRequestHeaders).totalSize();
// System.out.printf("gRPC Request Headers: %d bytes%nNetty Request Headers: %d bytes%n",
// grpcRequestHeadersBytes, defaultRequestHeadersBytes);
// Http2Headers grpcResponseHeaders = new GrpcHttp2RequestHeaders(4);
// Http2Headers defaultResponseHeaders = new DefaultHttp2Headers(true, 9);
// for (int i = 0; i < responseHeaders.length; i += 2) {
// grpcResponseHeaders.add(responseHeaders[i], responseHeaders[i + 1]);
// defaultResponseHeaders.add(responseHeaders[i], responseHeaders[i + 1]);
// }
// long grpcResponseHeadersBytes = GraphLayout.parseInstance(grpcResponseHeaders).totalSize();
// long defaultResponseHeadersBytes =
// GraphLayout.parseInstance(defaultResponseHeaders).totalSize();
// System.out.printf("gRPC Response Headers: %d bytes%nNetty Response Headers: %d bytes%n",
// grpcResponseHeadersBytes, defaultResponseHeadersBytes);
//}
}
| InboundHeadersBenchmark |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/EntryPointAssertions_notIn_Test.java | {
"start": 1028,
"end": 1669
} | class ____ extends EntryPointAssertionsBaseTest {
@ParameterizedTest
@MethodSource("notInFunctions")
void should_create_allOf_condition_from_condition_array(Function<Object[], NotInFilter> notInFunction) {
// GIVEN
String[] names = { "joe", "jack" };
// WHEN
NotInFilter notInFilter = notInFunction.apply(names);
// THEN
then(notInFilter).extracting("filterParameter")
.isEqualTo(names);
}
private static Stream<Function<Object[], NotInFilter>> notInFunctions() {
return Stream.of(Assertions::notIn, BDDAssertions::notIn, withAssertions::notIn);
}
}
| EntryPointAssertions_notIn_Test |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/NodeBase.java | {
"start": 1025,
"end": 1142
} | interface ____
*
*/
@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
@InterfaceStability.Unstable
public | Node |
java | spring-projects__spring-boot | documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/sql/jdbctemplate/MyBean.java | {
"start": 807,
"end": 1078
} | class ____ {
private final JdbcTemplate jdbcTemplate;
public MyBean(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void doSomething() {
/* @chomp:line this.jdbcTemplate ... */ this.jdbcTemplate.execute("delete from customer");
}
}
| MyBean |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableThrottleFirstTest.java | {
"start": 1195,
"end": 10158
} | class ____ extends RxJavaTest {
private TestScheduler scheduler;
private Scheduler.Worker innerScheduler;
private Observer<String> observer;
@Before
public void before() {
scheduler = new TestScheduler();
innerScheduler = scheduler.createWorker();
observer = TestHelper.mockObserver();
}
@Test
public void throttlingWithDropCallbackCrashes() throws Throwable {
Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() {
@Override
public void subscribe(Observer<? super String> innerObserver) {
innerObserver.onSubscribe(Disposable.empty());
publishNext(innerObserver, 100, "one"); // publish as it's first
publishNext(innerObserver, 300, "two"); // skip as it's last within the first 400
publishNext(innerObserver, 900, "three"); // publish
publishNext(innerObserver, 905, "four"); // skip
publishCompleted(innerObserver, 1000); // Should be published as soon as the timeout expires.
}
});
Action whenDisposed = mock(Action.class);
Observable<String> sampled = source
.doOnDispose(whenDisposed)
.throttleFirst(400, TimeUnit.MILLISECONDS, scheduler, e -> {
if ("two".equals(e)) {
throw new TestException("forced");
}
});
sampled.subscribe(observer);
InOrder inOrder = inOrder(observer);
scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS);
inOrder.verify(observer, times(1)).onNext("one");
inOrder.verify(observer, times(1)).onError(any(TestException.class));
inOrder.verify(observer, times(0)).onNext("two");
inOrder.verify(observer, times(0)).onNext("three");
inOrder.verify(observer, times(0)).onNext("four");
inOrder.verify(observer, times(0)).onComplete();
inOrder.verifyNoMoreInteractions();
verify(whenDisposed).run();
}
@Test
public void throttlingWithDropCallback() {
Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() {
@Override
public void subscribe(Observer<? super String> innerObserver) {
innerObserver.onSubscribe(Disposable.empty());
publishNext(innerObserver, 100, "one"); // publish as it's first
publishNext(innerObserver, 300, "two"); // skip as it's last within the first 400
publishNext(innerObserver, 900, "three"); // publish
publishNext(innerObserver, 905, "four"); // skip
publishCompleted(innerObserver, 1000); // Should be published as soon as the timeout expires.
}
});
Observer<Object> dropCallbackObserver = TestHelper.mockObserver();
Observable<String> sampled = source.throttleFirst(400, TimeUnit.MILLISECONDS, scheduler, dropCallbackObserver::onNext);
sampled.subscribe(observer);
InOrder inOrder = inOrder(observer);
InOrder dropCallbackOrder = inOrder(dropCallbackObserver);
scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS);
inOrder.verify(observer, times(1)).onNext("one");
inOrder.verify(observer, times(0)).onNext("two");
dropCallbackOrder.verify(dropCallbackObserver, times(1)).onNext("two");
inOrder.verify(observer, times(1)).onNext("three");
inOrder.verify(observer, times(0)).onNext("four");
dropCallbackOrder.verify(dropCallbackObserver, times(1)).onNext("four");
inOrder.verify(observer, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
dropCallbackOrder.verifyNoMoreInteractions();
}
@Test
public void throttlingWithCompleted() {
Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() {
@Override
public void subscribe(Observer<? super String> innerObserver) {
innerObserver.onSubscribe(Disposable.empty());
publishNext(innerObserver, 100, "one"); // publish as it's first
publishNext(innerObserver, 300, "two"); // skip as it's last within the first 400
publishNext(innerObserver, 900, "three"); // publish
publishNext(innerObserver, 905, "four"); // skip
publishCompleted(innerObserver, 1000); // Should be published as soon as the timeout expires.
}
});
Observable<String> sampled = source.throttleFirst(400, TimeUnit.MILLISECONDS, scheduler);
sampled.subscribe(observer);
InOrder inOrder = inOrder(observer);
scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS);
inOrder.verify(observer, times(1)).onNext("one");
inOrder.verify(observer, times(0)).onNext("two");
inOrder.verify(observer, times(1)).onNext("three");
inOrder.verify(observer, times(0)).onNext("four");
inOrder.verify(observer, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
}
@Test
public void throttlingWithError() {
Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() {
@Override
public void subscribe(Observer<? super String> innerObserver) {
innerObserver.onSubscribe(Disposable.empty());
Exception error = new TestException();
publishNext(innerObserver, 100, "one"); // Should be published since it is first
publishNext(innerObserver, 200, "two"); // Should be skipped since onError will arrive before the timeout expires
publishError(innerObserver, 300, error); // Should be published as soon as the timeout expires.
}
});
Observable<String> sampled = source.throttleFirst(400, TimeUnit.MILLISECONDS, scheduler);
sampled.subscribe(observer);
InOrder inOrder = inOrder(observer);
scheduler.advanceTimeTo(400, TimeUnit.MILLISECONDS);
inOrder.verify(observer).onNext("one");
inOrder.verify(observer).onError(any(TestException.class));
inOrder.verifyNoMoreInteractions();
}
private <T> void publishCompleted(final Observer<T> innerObserver, long delay) {
innerScheduler.schedule(new Runnable() {
@Override
public void run() {
innerObserver.onComplete();
}
}, delay, TimeUnit.MILLISECONDS);
}
private <T> void publishError(final Observer<T> innerObserver, long delay, final Exception error) {
innerScheduler.schedule(new Runnable() {
@Override
public void run() {
innerObserver.onError(error);
}
}, delay, TimeUnit.MILLISECONDS);
}
private <T> void publishNext(final Observer<T> innerObserver, long delay, final T value) {
innerScheduler.schedule(new Runnable() {
@Override
public void run() {
innerObserver.onNext(value);
}
}, delay, TimeUnit.MILLISECONDS);
}
@Test
public void throttle() {
Observer<Integer> observer = TestHelper.mockObserver();
TestScheduler s = new TestScheduler();
PublishSubject<Integer> o = PublishSubject.create();
o.throttleFirst(500, TimeUnit.MILLISECONDS, s).subscribe(observer);
// send events with simulated time increments
s.advanceTimeTo(0, TimeUnit.MILLISECONDS);
o.onNext(1); // deliver
o.onNext(2); // skip
s.advanceTimeTo(501, TimeUnit.MILLISECONDS);
o.onNext(3); // deliver
s.advanceTimeTo(600, TimeUnit.MILLISECONDS);
o.onNext(4); // skip
s.advanceTimeTo(700, TimeUnit.MILLISECONDS);
o.onNext(5); // skip
o.onNext(6); // skip
s.advanceTimeTo(1001, TimeUnit.MILLISECONDS);
o.onNext(7); // deliver
s.advanceTimeTo(1501, TimeUnit.MILLISECONDS);
o.onComplete();
InOrder inOrder = inOrder(observer);
inOrder.verify(observer).onNext(1);
inOrder.verify(observer).onNext(3);
inOrder.verify(observer).onNext(7);
inOrder.verify(observer).onComplete();
inOrder.verifyNoMoreInteractions();
}
@Test
public void throttleFirstDefaultScheduler() {
Observable.just(1).throttleFirst(100, TimeUnit.MILLISECONDS)
.test()
.awaitDone(5, TimeUnit.SECONDS)
.assertResult(1);
}
@Test
public void dispose() {
TestHelper.checkDisposed(Observable.just(1).throttleFirst(1, TimeUnit.DAYS));
}
@Test
public void doubleOnSubscribe() {
TestHelper.checkDoubleOnSubscribeObservable(o -> o.throttleFirst(1, TimeUnit.SECONDS));
}
}
| ObservableThrottleFirstTest |
java | elastic__elasticsearch | x-pack/plugin/eql/src/test/java/org/elasticsearch/xpack/eql/execution/sequence/CircuitBreakerTests.java | {
"start": 17387,
"end": 19715
} | class ____ extends NoOpClient {
private final AtomicLong pitContextCounter = new AtomicLong();
protected final CircuitBreaker circuitBreaker;
// private final String pitId;
private int searchRequestsRemainingCount;
private final BytesReference pitId = new BytesArray("test_pit_id");
ESMockClient(ThreadPool threadPool, CircuitBreaker circuitBreaker, int searchRequestsRemainingCount) {
super(threadPool);
this.circuitBreaker = circuitBreaker;
this.searchRequestsRemainingCount = searchRequestsRemainingCount;
}
abstract <Response extends ActionResponse> void handleSearchRequest(ActionListener<Response> listener, SearchRequest searchRequest);
@SuppressWarnings("unchecked")
@Override
protected <Request extends ActionRequest, Response extends ActionResponse> void doExecute(
ActionType<Response> action,
Request request,
ActionListener<Response> listener
) {
if (request instanceof OpenPointInTimeRequest) {
pitContextCounter.incrementAndGet();
OpenPointInTimeResponse response = new OpenPointInTimeResponse(pitId, 1, 1, 0, 0);
listener.onResponse((Response) response);
} else if (request instanceof ClosePointInTimeRequest) {
ClosePointInTimeResponse response = new ClosePointInTimeResponse(true, 1);
assert pitContextCounter.get() > 0;
pitContextCounter.decrementAndGet();
listener.onResponse((Response) response);
} else if (request instanceof SearchRequest searchRequest) {
searchRequestsRemainingCount--;
assertTrue(searchRequestsRemainingCount >= 0);
assertEquals(0, circuitBreaker.getTrippedCount());
handleSearchRequest(listener, searchRequest);
assert pitContextCounter.get() == 0;
} else {
super.doExecute(action, request, listener);
}
}
int searchRequestsRemainingCount() {
return searchRequestsRemainingCount;
}
}
/*
* For a successful sequence request, there will be two search requests expected
*/
private | ESMockClient |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/MetadataAwareAspectInstanceFactory.java | {
"start": 1066,
"end": 1488
} | interface ____ extends AspectInstanceFactory {
/**
* Get the AspectJ AspectMetadata for this factory's aspect.
* @return the aspect metadata
*/
AspectMetadata getAspectMetadata();
/**
* Get the best possible creation mutex for this factory.
* @return the mutex object (may be {@code null} for no mutex to use)
* @since 4.3
*/
@Nullable Object getAspectCreationMutex();
}
| MetadataAwareAspectInstanceFactory |
java | apache__logging-log4j2 | log4j-taglib/src/main/java/org/apache/logging/log4j/taglib/LogTag.java | {
"start": 969,
"end": 1382
} | class ____ extends LoggingMessageTagSupport {
private static final long serialVersionUID = 1L;
private Level level;
@Override
protected void init() {
super.init();
this.level = null;
}
@Override
protected Level getLevel() {
return this.level;
}
public void setLevel(final Object level) {
this.level = TagUtils.resolveLevel(level);
}
}
| LogTag |
java | apache__flink | flink-streaming-java/src/test/java/org/apache/flink/streaming/api/functions/PrintSinkTest.java | {
"start": 8053,
"end": 8676
} | class ____ implements MailboxExecutor {
@Override
public void execute(
MailOptions mailOptions,
ThrowingRunnable<? extends Exception> command,
String descriptionFormat,
Object... descriptionArgs) {}
@Override
public void yield() throws InterruptedException, FlinkRuntimeException {}
@Override
public boolean tryYield() throws FlinkRuntimeException {
return false;
}
@Override
public boolean shouldInterrupt() {
return false;
}
}
}
| DummyMailboxExecutor |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Finished.java | {
"start": 2729,
"end": 3386
} | class ____ implements StateFactory<Finished> {
private final Context context;
private final Logger log;
private final ArchivedExecutionGraph archivedExecutionGraph;
public Factory(Context context, ArchivedExecutionGraph archivedExecutionGraph, Logger log) {
this.context = context;
this.log = log;
this.archivedExecutionGraph = archivedExecutionGraph;
}
public Class<Finished> getStateClass() {
return Finished.class;
}
public Finished getState() {
return new Finished(context, archivedExecutionGraph, log);
}
}
}
| Factory |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/authorize/TestDefaultImpersonationProvider.java | {
"start": 1234,
"end": 1298
} | class ____ @DefaultImpersonationProvider
*/
@Timeout(10)
public | for |
java | apache__camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultPeriodTaskResolver.java | {
"start": 969,
"end": 1424
} | class ____ implements PeriodTaskResolver {
private final FactoryFinder finder;
public DefaultPeriodTaskResolver(FactoryFinder finder) {
this.finder = finder;
}
@Override
public Optional<Object> newInstance(String key) {
return finder.newInstance(key);
}
@Override
public <T> Optional<T> newInstance(String key, Class<T> type) {
return finder.newInstance(key, type);
}
}
| DefaultPeriodTaskResolver |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/runc/RuncContainerExecutorConfig.java | {
"start": 5920,
"end": 7270
} | class ____ {
final private OCIRootConfig root;
final private List<OCIMount> mounts;
final private OCIProcessConfig process;
final private OCIHooksConfig hooks;
final private OCIAnnotationsConfig annotations;
final private OCILinuxConfig linux;
public OCIRootConfig getRoot() {
return root;
}
public List<OCIMount> getMounts() {
return mounts;
}
public OCIProcessConfig getProcess() {
return process;
}
public String getHostname() {
return hostname;
}
public OCIHooksConfig getHooks() {
return hooks;
}
public OCIAnnotationsConfig getAnnotations() {
return annotations;
}
public OCILinuxConfig getLinux() {
return linux;
}
final private String hostname;
public OCIRuntimeConfig() {
this(null, null, null, null, null, null, null);
}
public OCIRuntimeConfig(OCIRootConfig root, List<OCIMount> mounts,
OCIProcessConfig process, String hostname,
OCIHooksConfig hooks,
OCIAnnotationsConfig annotations,
OCILinuxConfig linux) {
this.root = root;
this.mounts = mounts;
this.process = process;
this.hostname = hostname;
this.hooks = hooks;
this.annotations = annotations;
this.linux= linux;
}
/**
* This | OCIRuntimeConfig |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/ManagedSnapshotContext.java | {
"start": 908,
"end": 1126
} | interface ____ a context in which operators that use managed state (i.e. state that is
* managed by state backends) can perform a snapshot. As snapshots of the backends themselves are
* taken by the system, this | provides |
java | grpc__grpc-java | xds/src/main/java/io/grpc/xds/VirtualHost.java | {
"start": 7873,
"end": 8558
} | class ____ {
abstract String name();
abstract long weight();
abstract ImmutableMap<String, FilterConfig> filterConfigOverrides();
static ClusterWeight create(
String name, long weight, Map<String, FilterConfig> filterConfigOverrides) {
checkArgument(weight >= 0, "weight must not be negative");
return new AutoValue_VirtualHost_Route_RouteAction_ClusterWeight(
name, weight, ImmutableMap.copyOf(filterConfigOverrides));
}
}
// Configuration for the route's hashing policy if the upstream cluster uses a hashing load
// balancer.
@AutoValue
abstract static | ClusterWeight |
java | elastic__elasticsearch | x-pack/plugin/sql/sql-proto/src/main/java/org/elasticsearch/xpack/sql/proto/SqlQueryRequest.java | {
"start": 591,
"end": 8067
} | class ____ extends AbstractSqlRequest {
@Nullable
private final String cursor;
private final String query;
private final ZoneId zoneId;
private final String catalog;
private final int fetchSize;
private final TimeValue requestTimeout;
private final TimeValue pageTimeout;
private final Boolean columnar;
private final List<SqlTypedParamValue> params;
private final boolean fieldMultiValueLeniency;
private final boolean indexIncludeFrozen;
private final Boolean binaryCommunication;
// Async settings
private final TimeValue waitForCompletionTimeout;
private final boolean keepOnCompletion;
private final TimeValue keepAlive;
private final boolean allowPartialSearchResults;
public SqlQueryRequest(
String query,
List<SqlTypedParamValue> params,
ZoneId zoneId,
String catalog,
int fetchSize,
TimeValue requestTimeout,
TimeValue pageTimeout,
Boolean columnar,
String cursor,
RequestInfo requestInfo,
boolean fieldMultiValueLeniency,
boolean indexIncludeFrozen,
Boolean binaryCommunication,
TimeValue waitForCompletionTimeout,
boolean keepOnCompletion,
TimeValue keepAlive,
boolean allowPartialSearchResults
) {
super(requestInfo);
this.query = query;
this.params = params;
this.zoneId = zoneId;
this.catalog = catalog;
this.fetchSize = fetchSize;
this.requestTimeout = requestTimeout;
this.pageTimeout = pageTimeout;
this.columnar = columnar;
this.cursor = cursor;
this.fieldMultiValueLeniency = fieldMultiValueLeniency;
this.indexIncludeFrozen = indexIncludeFrozen;
this.binaryCommunication = binaryCommunication;
this.waitForCompletionTimeout = waitForCompletionTimeout;
this.keepOnCompletion = keepOnCompletion;
this.keepAlive = keepAlive;
this.allowPartialSearchResults = allowPartialSearchResults;
}
public SqlQueryRequest(
String query,
List<SqlTypedParamValue> params,
ZoneId zoneId,
String catalog,
int fetchSize,
TimeValue requestTimeout,
TimeValue pageTimeout,
Boolean columnar,
String cursor,
RequestInfo requestInfo,
boolean fieldMultiValueLeniency,
boolean indexIncludeFrozen,
Boolean binaryCommunication,
boolean allowPartialSearchResults
) {
this(
query,
params,
zoneId,
catalog,
fetchSize,
requestTimeout,
pageTimeout,
columnar,
cursor,
requestInfo,
fieldMultiValueLeniency,
indexIncludeFrozen,
binaryCommunication,
CoreProtocol.DEFAULT_WAIT_FOR_COMPLETION_TIMEOUT,
CoreProtocol.DEFAULT_KEEP_ON_COMPLETION,
CoreProtocol.DEFAULT_KEEP_ALIVE,
allowPartialSearchResults
);
}
public SqlQueryRequest(
String cursor,
TimeValue requestTimeout,
TimeValue pageTimeout,
RequestInfo requestInfo,
boolean binaryCommunication,
boolean allowPartialSearchResults
) {
this(
"",
emptyList(),
CoreProtocol.TIME_ZONE,
null,
CoreProtocol.FETCH_SIZE,
requestTimeout,
pageTimeout,
false,
cursor,
requestInfo,
CoreProtocol.FIELD_MULTI_VALUE_LENIENCY,
CoreProtocol.INDEX_INCLUDE_FROZEN,
binaryCommunication,
allowPartialSearchResults
);
}
/**
* The key that must be sent back to SQL to access the next page of
* results.
*/
public String cursor() {
return cursor;
}
/**
* Text of SQL query
*/
public String query() {
return query;
}
/**
* An optional list of parameters if the SQL query is parametrized
*/
public List<SqlTypedParamValue> params() {
return params;
}
/**
* The client's time zone
*/
public ZoneId zoneId() {
return zoneId;
}
public String catalog() {
return catalog;
}
/**
* Hint about how many results to fetch at once.
*/
public int fetchSize() {
return fetchSize;
}
/**
* The timeout specified on the search request
*/
public TimeValue requestTimeout() {
return requestTimeout;
}
/**
* The scroll timeout
*/
public TimeValue pageTimeout() {
return pageTimeout;
}
/**
* Optional setting for returning the result values in a columnar fashion (as opposed to rows of values).
* Each column will have all its values in a list. Defaults to false.
*/
public Boolean columnar() {
return columnar;
}
public boolean fieldMultiValueLeniency() {
return fieldMultiValueLeniency;
}
public boolean indexIncludeFrozen() {
return indexIncludeFrozen;
}
public Boolean binaryCommunication() {
return binaryCommunication;
}
public TimeValue waitForCompletionTimeout() {
return waitForCompletionTimeout;
}
public boolean keepOnCompletion() {
return keepOnCompletion;
}
public TimeValue keepAlive() {
return keepAlive;
}
public boolean allowPartialSearchResults() {
return allowPartialSearchResults;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (super.equals(o) == false) {
return false;
}
SqlQueryRequest that = (SqlQueryRequest) o;
return fetchSize == that.fetchSize
&& fieldMultiValueLeniency == that.fieldMultiValueLeniency
&& indexIncludeFrozen == that.indexIncludeFrozen
&& keepOnCompletion == that.keepOnCompletion
&& allowPartialSearchResults == that.allowPartialSearchResults
&& Objects.equals(query, that.query)
&& Objects.equals(params, that.params)
&& Objects.equals(zoneId, that.zoneId)
&& Objects.equals(catalog, that.catalog)
&& Objects.equals(requestTimeout, that.requestTimeout)
&& Objects.equals(pageTimeout, that.pageTimeout)
&& Objects.equals(columnar, that.columnar)
&& Objects.equals(cursor, that.cursor)
&& Objects.equals(binaryCommunication, that.binaryCommunication)
&& Objects.equals(waitForCompletionTimeout, that.waitForCompletionTimeout)
&& Objects.equals(keepAlive, that.keepAlive);
}
@Override
public int hashCode() {
return Objects.hash(
super.hashCode(),
query,
zoneId,
catalog,
fetchSize,
requestTimeout,
pageTimeout,
columnar,
cursor,
fieldMultiValueLeniency,
indexIncludeFrozen,
binaryCommunication,
waitForCompletionTimeout,
keepOnCompletion,
keepAlive,
allowPartialSearchResults
);
}
}
| SqlQueryRequest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.