language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/DefaultConsumer.java | {
"start": 6708,
"end": 7596
} | interface ____ the configured processor on the consumer. If the
* processor does not implement the interface, it will be adapted so that it does.
*/
public AsyncProcessor getAsyncProcessor() {
return asyncProcessor;
}
public ExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
public void setExceptionHandler(ExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
@Override
public void setHealthCheck(HealthCheck healthCheck) {
this.healthCheck = healthCheck;
}
@Override
public HealthCheck getHealthCheck() {
return healthCheck;
}
@Override
protected void doBuild() throws Exception {
LOG.debug("Build consumer: {}", this);
ServiceHelper.buildService(exchangeFactory, processor);
// force creating and load the | to |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/jdk8/FlowableMapOptionalTest.java | {
"start": 1214,
"end": 13879
} | class ____ extends RxJavaTest {
static final Function<? super Integer, Optional<? extends Integer>> MODULO = v -> v % 2 == 0 ? Optional.of(v) : Optional.<Integer>empty();
@Test
public void allPresent() {
Flowable.range(1, 5)
.mapOptional(Optional::of)
.test()
.assertResult(1, 2, 3, 4, 5);
}
@Test
public void allEmpty() {
Flowable.range(1, 5)
.mapOptional(v -> Optional.<Integer>empty())
.test()
.assertResult();
}
@Test
public void mixed() {
Flowable.range(1, 10)
.mapOptional(MODULO)
.test()
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void mapperChash() {
BehaviorProcessor<Integer> source = BehaviorProcessor.createDefault(1);
source
.mapOptional(v -> { throw new TestException(); })
.test()
.assertFailure(TestException.class);
assertFalse(source.hasSubscribers());
}
@Test
public void mapperNull() {
BehaviorProcessor<Integer> source = BehaviorProcessor.createDefault(1);
source
.mapOptional(v -> null)
.test()
.assertFailure(NullPointerException.class);
assertFalse(source.hasSubscribers());
}
@Test
public void crashDropsOnNexts() {
Flowable<Integer> source = new Flowable<Integer>() {
@Override
protected void subscribeActual(Subscriber<? super Integer> s) {
s.onSubscribe(new BooleanSubscription());
s.onNext(1);
s.onNext(2);
}
};
source
.mapOptional(v -> { throw new TestException(); })
.test()
.assertFailure(TestException.class);
}
@Test
public void backpressureAll() {
Flowable.range(1, 5)
.mapOptional(Optional::of)
.test(0L)
.assertEmpty()
.requestMore(2)
.assertValuesOnly(1, 2)
.requestMore(2)
.assertValuesOnly(1, 2, 3, 4)
.requestMore(1)
.assertResult(1, 2, 3, 4, 5);
}
@Test
public void backpressureNone() {
Flowable.range(1, 5)
.mapOptional(v -> Optional.empty())
.test(1L)
.assertResult();
}
@Test
public void backpressureMixed() {
Flowable.range(1, 10)
.mapOptional(MODULO)
.test(0L)
.assertEmpty()
.requestMore(2)
.assertValuesOnly(2, 4)
.requestMore(2)
.assertValuesOnly(2, 4, 6, 8)
.requestMore(1)
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void syncFusedAll() {
Flowable.range(1, 5)
.mapOptional(Optional::of)
.to(TestHelper.testConsumer(false, QueueFuseable.SYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.SYNC)
.assertResult(1, 2, 3, 4, 5);
}
@Test
public void asyncFusedAll() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5);
up
.mapOptional(Optional::of)
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.ASYNC)
.assertResult(1, 2, 3, 4, 5);
}
@Test
public void boundaryFusedAll() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5);
up
.mapOptional(Optional::of)
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC | QueueFuseable.BOUNDARY))
.assertFuseable()
.assertFusionMode(QueueFuseable.NONE)
.assertResult(1, 2, 3, 4, 5);
}
@Test
public void syncFusedNone() {
Flowable.range(1, 5)
.mapOptional(v -> Optional.empty())
.to(TestHelper.testConsumer(false, QueueFuseable.SYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.SYNC)
.assertResult();
}
@Test
public void asyncFusedNone() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5);
up
.mapOptional(v -> Optional.empty())
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.ASYNC)
.assertResult();
}
@Test
public void boundaryFusedNone() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5);
up
.mapOptional(v -> Optional.empty())
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC | QueueFuseable.BOUNDARY))
.assertFuseable()
.assertFusionMode(QueueFuseable.NONE)
.assertResult();
}
@Test
public void syncFusedMixed() {
Flowable.range(1, 10)
.mapOptional(MODULO)
.to(TestHelper.testConsumer(false, QueueFuseable.SYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.SYNC)
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void asyncFusedMixed() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
up
.mapOptional(MODULO)
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.ASYNC)
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void boundaryFusedMixed() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
up
.mapOptional(MODULO)
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC | QueueFuseable.BOUNDARY))
.assertFuseable()
.assertFusionMode(QueueFuseable.NONE)
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void allPresentConditional() {
Flowable.range(1, 5)
.mapOptional(Optional::of)
.filter(v -> true)
.test()
.assertResult(1, 2, 3, 4, 5);
}
@Test
public void allEmptyConditional() {
Flowable.range(1, 5)
.mapOptional(v -> Optional.<Integer>empty())
.filter(v -> true)
.test()
.assertResult();
}
@Test
public void mixedConditional() {
Flowable.range(1, 10)
.mapOptional(MODULO)
.filter(v -> true)
.test()
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void mapperChashConditional() {
BehaviorProcessor<Integer> source = BehaviorProcessor.createDefault(1);
source
.mapOptional(v -> { throw new TestException(); })
.filter(v -> true)
.test()
.assertFailure(TestException.class);
assertFalse(source.hasSubscribers());
}
@Test
public void mapperNullConditional() {
BehaviorProcessor<Integer> source = BehaviorProcessor.createDefault(1);
source
.mapOptional(v -> null)
.filter(v -> true)
.test()
.assertFailure(NullPointerException.class);
assertFalse(source.hasSubscribers());
}
@Test
public void crashDropsOnNextsConditional() {
Flowable<Integer> source = new Flowable<Integer>() {
@Override
protected void subscribeActual(Subscriber<? super Integer> s) {
s.onSubscribe(new BooleanSubscription());
s.onNext(1);
s.onNext(2);
}
};
source
.mapOptional(v -> { throw new TestException(); })
.filter(v -> true)
.test()
.assertFailure(TestException.class);
}
@Test
public void backpressureAllConditional() {
Flowable.range(1, 5)
.mapOptional(Optional::of)
.filter(v -> true)
.test(0L)
.assertEmpty()
.requestMore(2)
.assertValuesOnly(1, 2)
.requestMore(2)
.assertValuesOnly(1, 2, 3, 4)
.requestMore(1)
.assertResult(1, 2, 3, 4, 5);
}
@Test
public void backpressureNoneConditional() {
Flowable.range(1, 5)
.mapOptional(v -> Optional.empty())
.filter(v -> true)
.test(1L)
.assertResult();
}
@Test
public void backpressureMixedConditional() {
Flowable.range(1, 10)
.mapOptional(MODULO)
.filter(v -> true)
.test(0L)
.assertEmpty()
.requestMore(2)
.assertValuesOnly(2, 4)
.requestMore(2)
.assertValuesOnly(2, 4, 6, 8)
.requestMore(1)
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void syncFusedAllConditional() {
Flowable.range(1, 5)
.mapOptional(Optional::of)
.filter(v -> true)
.to(TestHelper.testConsumer(false, QueueFuseable.SYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.SYNC)
.assertResult(1, 2, 3, 4, 5);
}
@Test
public void asyncFusedAllConditional() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5);
up
.mapOptional(Optional::of)
.filter(v -> true)
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.ASYNC)
.assertResult(1, 2, 3, 4, 5);
}
@Test
public void boundaryFusedAllConditiona() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5);
up
.mapOptional(Optional::of)
.filter(v -> true)
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC | QueueFuseable.BOUNDARY))
.assertFuseable()
.assertFusionMode(QueueFuseable.NONE)
.assertResult(1, 2, 3, 4, 5);
}
@Test
public void syncFusedNoneConditional() {
Flowable.range(1, 5)
.mapOptional(v -> Optional.empty())
.filter(v -> true)
.to(TestHelper.testConsumer(false, QueueFuseable.SYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.SYNC)
.assertResult();
}
@Test
public void asyncFusedNoneConditional() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5);
up
.mapOptional(v -> Optional.empty())
.filter(v -> true)
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.ASYNC)
.assertResult();
}
@Test
public void boundaryFusedNoneConditional() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5);
up
.mapOptional(v -> Optional.empty())
.filter(v -> true)
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC | QueueFuseable.BOUNDARY))
.assertFuseable()
.assertFusionMode(QueueFuseable.NONE)
.assertResult();
}
@Test
public void syncFusedMixedConditional() {
Flowable.range(1, 10)
.mapOptional(MODULO)
.filter(v -> true)
.to(TestHelper.testConsumer(false, QueueFuseable.SYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.SYNC)
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void asyncFusedMixedConditional() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
up
.mapOptional(MODULO)
.filter(v -> true)
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC))
.assertFuseable()
.assertFusionMode(QueueFuseable.ASYNC)
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void boundaryFusedMixedConditional() {
UnicastProcessor<Integer> up = UnicastProcessor.create();
TestHelper.emit(up, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
up
.mapOptional(MODULO)
.filter(v -> true)
.to(TestHelper.testConsumer(false, QueueFuseable.ASYNC | QueueFuseable.BOUNDARY))
.assertFuseable()
.assertFusionMode(QueueFuseable.NONE)
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void conditionalFusionNoNPE() {
TestSubscriberEx<Object> ts = new TestSubscriberEx<>()
.setInitialFusionMode(QueueFuseable.ANY);
Flowable.empty()
.observeOn(ImmediateThinScheduler.INSTANCE)
.filter(v -> true)
.mapOptional(Optional::of)
.filter(v -> true)
.subscribe(ts)
;
ts.assertResult();
}
}
| FlowableMapOptionalTest |
java | qos-ch__slf4j | jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SimpleLog.java | {
"start": 20451,
"end": 20794
} | class ____,
* or if security permissions are restricted.
*
* In the first case (not related), we want to ignore and keep going.
* We cannot help but also ignore the second with the logic below, but
* other calls elsewhere (to obtain a | loader |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/hashset/HashSetAssert_doesNotHaveDuplicates_Test.java | {
"start": 1214,
"end": 2570
} | class ____ extends HashSetAssertBaseTest {
@Override
protected HashSetAssert<Object> invoke_api_method() {
return assertions.doesNotHaveDuplicates();
}
@Override
protected void verify_internal_effects() {
verify(iterables).assertDoesNotHaveDuplicates(getInfo(assertions), getActual(assertions));
}
@HashSetTest
void should_pass(HashSetFactory hashSetFactory) {
// GIVEN
HashSet<String> hashSet = hashSetFactory.createWith("Yoda", "Yoda", "Luke", "Han");
// WHEN/THEN
then(hashSet).doesNotHaveDuplicates();
}
@HashSetTest
void should_fail_for_elements_with_changed_hashCode(HashSetFactory hashSetFactory) {
// GIVEN
Date first = Date.from(EPOCH.plusSeconds(1));
Date second = Date.from(EPOCH.plusSeconds(3));
HashSet<Date> dates = hashSetFactory.createWith(first, second);
first.setTime(3_000);
// WHEN
var assertionError = expectAssertionError(() -> assertThat(dates).doesNotHaveDuplicates());
// THEN
var message = shouldNotHaveDuplicates(dates, newLinkedHashSet(first)).create()
+ "(elements were checked as in HashSet, as soon as their hashCode change, the HashSet won't find them anymore - use skippingHashCodeComparison to get a collection like comparison)";
then(assertionError).hasMessage(message);
}
}
| HashSetAssert_doesNotHaveDuplicates_Test |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/EditLogTailer.java | {
"start": 21665,
"end": 24476
} | class ____<T> implements Callable<T> {
/**
* Do the actual work to the remote namenode via the {@link #cachedActiveProxy}.
* @return the result of the work, if there is one
* @throws IOException if the actions done to the proxy throw an exception.
*/
protected abstract T doWork() throws IOException;
public T call() throws IOException {
// reset the loop count on success
nnLoopCount = 0;
while ((cachedActiveProxy = getActiveNodeProxy()) != null) {
try {
T ret = doWork();
return ret;
} catch (IOException e) {
LOG.warn("Exception from remote name node " + currentNN
+ ", try next.", e);
// Try next name node if exception happens.
cachedActiveProxy = null;
nnLoopCount++;
}
}
throw new IOException("Cannot find any valid remote NN to service request!");
}
private NamenodeProtocol getActiveNodeProxy() throws IOException {
if (cachedActiveProxy == null) {
while (true) {
// If the thread is interrupted, quit by returning null.
if (Thread.currentThread().isInterrupted()) {
LOG.warn("Interrupted while trying to getActiveNodeProxy.");
return null;
}
// if we have reached the max loop count, quit by returning null
if ((nnLoopCount / nnCount) >= maxRetries) {
LOG.warn("Have reached the max loop count ({}).", nnLoopCount);
return null;
}
currentNN = nnLookup.next();
try {
int rpcTimeout = conf.getInt(
DFSConfigKeys.DFS_HA_LOGROLL_RPC_TIMEOUT_KEY,
DFSConfigKeys.DFS_HA_LOGROLL_RPC_TIMEOUT_DEFAULT);
NamenodeProtocolPB proxy = RPC.waitForProxy(NamenodeProtocolPB.class,
RPC.getProtocolVersion(NamenodeProtocolPB.class), currentNN.getIpcAddress(), conf,
rpcTimeout, Long.MAX_VALUE);
cachedActiveProxy = new NamenodeProtocolTranslatorPB(proxy);
break;
} catch (IOException e) {
LOG.info("Failed to reach " + currentNN, e);
// couldn't even reach this NN, try the next one
nnLoopCount++;
}
}
}
assert cachedActiveProxy != null;
return cachedActiveProxy;
}
}
@VisibleForTesting
public NamenodeProtocol getCachedActiveProxy() {
return cachedActiveProxy;
}
@VisibleForTesting
public long getLastRollTimeMs() {
return lastRollTimeMs;
}
@VisibleForTesting
public RemoteNameNodeInfo getCurrentNN() {
return currentNN;
}
@VisibleForTesting
public void setShouldRunForTest(boolean shouldRun) {
this.tailerThread.setShouldRun(shouldRun);
}
}
| MultipleNameNodeProxy |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/cloud/ServiceLoadBalancerFunction.java | {
"start": 976,
"end": 1088
} | interface ____<T> {
T apply(ServiceDefinition serviceDefinition) throws Exception;
}
| ServiceLoadBalancerFunction |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/event/spi/PreCollectionRecreateEventListener.java | {
"start": 210,
"end": 324
} | interface ____ {
void onPreRecreateCollection(PreCollectionRecreateEvent event);
}
| PreCollectionRecreateEventListener |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/job/metrics/DoubleAccumulator.java | {
"start": 6402,
"end": 7335
} | class ____ implements DoubleAccumulator {
public static final String NAME = "avg";
private double sum;
private int count;
private DoubleAverage(double init) {
sum = init;
count = 1;
}
@Override
public void add(double value) {
this.sum += value;
this.count++;
}
@Override
public double getValue() {
return sum / count;
}
@Override
public String getName() {
return NAME;
}
}
/**
* {@link DoubleAccumulator} that returns the skew percentage over all values. Uses a version of
* the Coefficient of Variation (CV) statistic to calculate skew. This version of CV uses
* average absolute deviation, instead of std deviation. This method currently assumes a dataset
* of positive numbers and 0.
*/
final | DoubleAverage |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/bzip2/TestBZip2TextFileWriter.java | {
"start": 1253,
"end": 2864
} | class ____ {
private static final byte[] DELIMITER = new byte[] {'\0'};
private ByteArrayOutputStream rawOut;
private BZip2TextFileWriter writer;
@BeforeEach
public void setUp() throws Exception {
rawOut = new ByteArrayOutputStream();
writer = new BZip2TextFileWriter(rawOut);
}
@AfterEach
public void tearDown() throws Exception {
rawOut = null;
writer.close();
}
@Test
public void writingSingleBlockSizeOfData() throws Exception {
writer.writeRecord(BLOCK_SIZE, DELIMITER);
writer.close();
List<Long> nextBlocks = getNextBlockMarkerOffsets();
assertEquals(0, nextBlocks.size());
}
@Test
public void justExceedingBeyondBlockSize() throws Exception {
writer.writeRecord(BLOCK_SIZE + 1, DELIMITER);
writer.close();
List<Long> nextBlocks = getNextBlockMarkerOffsets();
assertEquals(1, nextBlocks.size());
}
@Test
public void writingTwoBlockSizesOfData() throws Exception {
writer.writeRecord(2 * BLOCK_SIZE, DELIMITER);
writer.close();
List<Long> nextBlocks = getNextBlockMarkerOffsets();
assertEquals(1, nextBlocks.size());
}
@Test
public void justExceedingBeyondTwoBlocks() throws Exception {
writer.writeRecord(2 * BLOCK_SIZE + 1, DELIMITER);
writer.close();
List<Long> nextBlocks = getNextBlockMarkerOffsets();
assertEquals(2, nextBlocks.size());
}
private List<Long> getNextBlockMarkerOffsets() throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(rawOut.toByteArray());
return BZip2Utils.getNextBlockMarkerOffsets(in);
}
} | TestBZip2TextFileWriter |
java | netty__netty | example/src/main/java/io/netty/example/http/cors/OkResponseHandler.java | {
"start": 1175,
"end": 1643
} | class ____ extends SimpleChannelInboundHandler<Object> {
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) {
final FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER);
response.headers().set("custom-response-header", "Some value");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}
| OkResponseHandler |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/multipart/MultipartCleanupTest.java | {
"start": 2940,
"end": 3122
} | class ____ {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String upload(@MultipartForm Form form) {
return "test";
}
}
}
| Resource |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilterTests.java | {
"start": 3161,
"end": 3479
} | class ____ implements WebFilterChain {
private HttpMethod httpMethod;
public HttpMethod getHttpMethod() {
return this.httpMethod;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange) {
this.httpMethod = exchange.getRequest().getMethod();
return Mono.empty();
}
}
}
| TestWebFilterChain |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/ServiceEvent.java | {
"start": 1081,
"end": 2318
} | class ____ extends AbstractEvent<ServiceEventType> {
private final ServiceEventType type;
private String version;
private boolean autoFinalize;
private boolean expressUpgrade;
// For express upgrade they should be in order.
private List<Component> compsToUpgrade;
public ServiceEvent(ServiceEventType serviceEventType) {
super(serviceEventType);
this.type = serviceEventType;
}
public ServiceEventType getType() {
return type;
}
public String getVersion() {
return version;
}
public ServiceEvent setVersion(String version) {
this.version = version;
return this;
}
public boolean isAutoFinalize() {
return autoFinalize;
}
public ServiceEvent setAutoFinalize(boolean autoFinalize) {
this.autoFinalize = autoFinalize;
return this;
}
public boolean isExpressUpgrade() {
return expressUpgrade;
}
public ServiceEvent setExpressUpgrade(boolean expressUpgrade) {
this.expressUpgrade = expressUpgrade;
return this;
}
public List<Component> getCompsToUpgrade() {
return compsToUpgrade;
}
public ServiceEvent setCompsToUpgrade(List<Component> compsToUpgrade) {
this.compsToUpgrade = compsToUpgrade;
return this;
}
}
| ServiceEvent |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/runtime/jobmaster/JobMasterTriggerSavepointITCase.java | {
"start": 16308,
"end": 18376
} | class ____ extends AbstractInvokable {
public NoOpBlockingInvokable(final Environment environment) {
super(environment);
}
@Override
public void invoke() {
invokeLatch.countDown();
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public CompletableFuture<Boolean> triggerCheckpointAsync(
final CheckpointMetaData checkpointMetaData,
final CheckpointOptions checkpointOptions) {
final TaskStateSnapshot checkpointStateHandles = new TaskStateSnapshot();
checkpointStateHandles.putSubtaskStateByOperatorID(
OperatorID.fromJobVertexID(getEnvironment().getJobVertexId()),
OperatorSubtaskState.builder().build());
getEnvironment()
.acknowledgeCheckpoint(
checkpointMetaData.getCheckpointId(),
new CheckpointMetrics(),
checkpointStateHandles);
triggerCheckpointLatch.countDown();
return CompletableFuture.completedFuture(true);
}
@Override
public Future<Void> notifyCheckpointCompleteAsync(final long checkpointId) {
return CompletableFuture.completedFuture(null);
}
@Override
public Future<Void> notifyCheckpointAbortAsync(
long checkpointId, long latestCompletedCheckpointId) {
return CompletableFuture.completedFuture(null);
}
}
private String cancelWithSavepoint(ClusterClient<?> clusterClient) throws Exception {
return clusterClient
.cancelWithSavepoint(
jobGraph.getJobID(),
savepointDirectory.toAbsolutePath().toString(),
SavepointFormatType.CANONICAL)
.get();
}
}
| NoOpBlockingInvokable |
java | apache__maven | compat/maven-model/src/main/java/org/apache/maven/model/InputLocationTracker.java | {
"start": 949,
"end": 1680
} | interface ____ {
// -----------/
// - Methods -/
// -----------/
/**
* Gets the location of the specified field in the input
* source.
*
* @param field The key of the field, must not be
* <code>null</code>.
* @return The location of the field in the input source or
* <code>null</code> if unknown.
*/
public InputLocation getLocation(Object field);
/**
* Sets the location of the specified field.
*
* @param field The key of the field, must not be
* <code>null</code>.
* @param location The location of the field, may be
* <code>null</code>.
*/
public void setLocation(Object field, InputLocation location);
}
| InputLocationTracker |
java | apache__avro | lang/java/trevni/core/src/main/java/org/apache/trevni/ColumnFileReader.java | {
"start": 1080,
"end": 5004
} | class ____ implements Closeable {
private Input file;
private long rowCount;
private int columnCount;
private ColumnFileMetaData metaData;
private ColumnDescriptor[] columns;
private Map<String, ColumnDescriptor> columnsByName;
/** Construct reading from the named file. */
public ColumnFileReader(File file) throws IOException {
this(new InputFile(file));
}
/** Construct reading from the provided input. */
public ColumnFileReader(Input file) throws IOException {
this.file = file;
readHeader();
}
/** Return the number of rows in this file. */
public long getRowCount() {
return rowCount;
}
/** Return the number of columns in this file. */
public long getColumnCount() {
return columnCount;
}
/** Return this file's metadata. */
public ColumnFileMetaData getMetaData() {
return metaData;
}
/** Return all columns' metadata. */
public ColumnMetaData[] getColumnMetaData() {
ColumnMetaData[] result = new ColumnMetaData[columnCount];
for (int i = 0; i < columnCount; i++)
result[i] = columns[i].metaData;
return result;
}
/** Return root columns' metadata. Roots are columns that have no parent. */
public List<ColumnMetaData> getRoots() {
List<ColumnMetaData> result = new ArrayList<>();
for (int i = 0; i < columnCount; i++)
if (columns[i].metaData.getParent() == null)
result.add(columns[i].metaData);
return result;
}
/** Return a column's metadata. */
public ColumnMetaData getColumnMetaData(int number) {
return columns[number].metaData;
}
/** Return a column's metadata. */
public ColumnMetaData getColumnMetaData(String name) {
return getColumn(name).metaData;
}
private <T extends Comparable> ColumnDescriptor<T> getColumn(String name) {
ColumnDescriptor column = columnsByName.get(name);
if (column == null)
throw new TrevniRuntimeException("No column named: " + name);
return (ColumnDescriptor<T>) column;
}
private void readHeader() throws IOException {
InputBuffer in = new InputBuffer(file, 0);
readMagic(in);
this.rowCount = in.readFixed64();
this.columnCount = in.readFixed32();
this.metaData = ColumnFileMetaData.read(in);
this.columnsByName = new HashMap<>(columnCount);
columns = new ColumnDescriptor[columnCount];
readColumnMetaData(in);
readColumnStarts(in);
}
private void readMagic(InputBuffer in) throws IOException {
byte[] magic = new byte[ColumnFileWriter.MAGIC.length];
try {
in.readFully(magic);
} catch (IOException e) {
throw new IOException("Not a data file.");
}
if (!(Arrays.equals(ColumnFileWriter.MAGIC, magic) || !Arrays.equals(ColumnFileWriter.MAGIC_1, magic)
|| !Arrays.equals(ColumnFileWriter.MAGIC_0, magic)))
throw new IOException("Not a data file.");
}
private void readColumnMetaData(InputBuffer in) throws IOException {
for (int i = 0; i < columnCount; i++) {
ColumnMetaData meta = ColumnMetaData.read(in, this);
meta.setDefaults(this.metaData);
ColumnDescriptor column = new ColumnDescriptor(file, meta);
columns[i] = column;
meta.setNumber(i);
columnsByName.put(meta.getName(), column);
}
}
private void readColumnStarts(InputBuffer in) throws IOException {
for (int i = 0; i < columnCount; i++)
columns[i].start = in.readFixed64();
}
/** Return an iterator over values in the named column. */
public <T extends Comparable> ColumnValues<T> getValues(String columnName) throws IOException {
return new ColumnValues<>(getColumn(columnName));
}
/** Return an iterator over values in a column. */
public <T extends Comparable> ColumnValues<T> getValues(int column) throws IOException {
return new ColumnValues<>(columns[column]);
}
@Override
public void close() throws IOException {
file.close();
}
}
| ColumnFileReader |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopLongIntAggregator.java | {
"start": 3127,
"end": 4358
} | class ____ implements GroupingAggregatorState {
private final LongIntBucketedSort sort;
private GroupingState(BigArrays bigArrays, int limit, boolean ascending) {
this.sort = new LongIntBucketedSort(bigArrays, ascending ? SortOrder.ASC : SortOrder.DESC, limit);
}
public void add(int groupId, long value, int outputValue) {
sort.collect(value, outputValue, groupId);
}
@Override
public void toIntermediate(Block[] blocks, int offset, IntVector selected, DriverContext driverContext) {
sort.toBlocks(driverContext.blockFactory(), blocks, offset, selected);
}
Block toBlock(BlockFactory blockFactory, IntVector selected) {
Block[] blocks = new Block[2];
sort.toBlocks(blockFactory, blocks, 0, selected);
Releasables.close(blocks[0]);
return blocks[1];
}
@Override
public void enableGroupIdTracking(SeenGroupIds seen) {
// we figure out seen values from nulls on the values block
}
@Override
public void close() {
Releasables.closeExpectNoException(sort);
}
}
public static | GroupingState |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/metrics/TokenBucketTest.java | {
"start": 1175,
"end": 3378
} | class ____ {
Time time;
@BeforeEach
public void setup() {
time = new MockTime(0, System.currentTimeMillis(), System.nanoTime());
}
@Test
public void testRecord() {
// Rate = 5 unit / sec
// Burst = 2 * 10 = 20 units
MetricConfig config = new MetricConfig()
.quota(Quota.upperBound(5))
.timeWindow(2, TimeUnit.SECONDS)
.samples(10);
TokenBucket tk = new TokenBucket();
// Expect 100 credits at T
assertEquals(100, tk.measure(config, time.milliseconds()), 0.1);
// Record 60 at T, expect 13 credits
tk.record(config, 60, time.milliseconds());
assertEquals(40, tk.measure(config, time.milliseconds()), 0.1);
// Advance by 2s, record 5, expect 45 credits
time.sleep(2000);
tk.record(config, 5, time.milliseconds());
assertEquals(45, tk.measure(config, time.milliseconds()), 0.1);
// Advance by 2s, record 60, expect -5 credits
time.sleep(2000);
tk.record(config, 60, time.milliseconds());
assertEquals(-5, tk.measure(config, time.milliseconds()), 0.1);
}
@Test
public void testUnrecord() {
// Rate = 5 unit / sec
// Burst = 2 * 10 = 20 units
MetricConfig config = new MetricConfig()
.quota(Quota.upperBound(5))
.timeWindow(2, TimeUnit.SECONDS)
.samples(10);
TokenBucket tk = new TokenBucket();
// Expect 100 credits at T
assertEquals(100, tk.measure(config, time.milliseconds()), 0.1);
// Record -60 at T, expect 100 credits
tk.record(config, -60, time.milliseconds());
assertEquals(100, tk.measure(config, time.milliseconds()), 0.1);
// Advance by 2s, record 60, expect 40 credits
time.sleep(2000);
tk.record(config, 60, time.milliseconds());
assertEquals(40, tk.measure(config, time.milliseconds()), 0.1);
// Advance by 2s, record -60, expect 100 credits
time.sleep(2000);
tk.record(config, -60, time.milliseconds());
assertEquals(100, tk.measure(config, time.milliseconds()), 0.1);
}
}
| TokenBucketTest |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/java/typeutils/PojoParametrizedTypeExtractionTest.java | {
"start": 2906,
"end": 3091
} | class ____ extends ParameterizedParent<Pojo> {
public double precise;
}
/** Representation of map function for type extraction. */
public static | ParameterizedParentImpl |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/parent_reference_3level/Comment.java | {
"start": 719,
"end": 1328
} | class ____ {
private int id;
private Post post;
private String comment;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
if (this.post != null) {
throw new RuntimeException("Setter called twice");
}
this.post = post;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
if (this.comment != null) {
throw new RuntimeException("Setter called twice");
}
this.comment = comment;
}
}
| Comment |
java | junit-team__junit5 | documentation/src/test/java/example/ParameterizedTestDemo.java | {
"start": 16641,
"end": 17657
} | class ____ extends SimpleArgumentsAggregator {
@Override
protected Person aggregateArguments(ArgumentsAccessor arguments, Class<?> targetType,
AnnotatedElementContext context, int parameterIndex) {
return new Person(
arguments.getString(0),
arguments.getString(1),
arguments.get(2, Gender.class),
arguments.get(3, LocalDate.class));
}
}
// end::ArgumentsAggregator_example_PersonAggregator[]
// @formatter:on
// @formatter:off
// tag::ArgumentsAggregator_with_custom_annotation_example[]
@ParameterizedTest
@CsvSource({
"Jane, Doe, F, 1990-05-20",
"John, Doe, M, 1990-10-22"
})
void testWithCustomAggregatorAnnotation(@CsvToPerson Person person) {
// perform assertions against person
}
// end::ArgumentsAggregator_with_custom_annotation_example[]
// tag::ArgumentsAggregator_with_custom_annotation_example_CsvToPerson[]
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@AggregateWith(PersonAggregator.class)
public @ | PersonAggregator |
java | google__guava | android/guava-tests/test/com/google/common/collect/TablesTransformValuesRowTest.java | {
"start": 919,
"end": 1612
} | class ____ extends RowTests {
public TablesTransformValuesRowTest() {
super(false, false, true, true, true);
}
@Override
Table<Character, String, Integer> makeTable() {
Table<Character, String, Integer> table = HashBasedTable.create();
return transformValues(table, TableCollectionTest.DIVIDE_BY_2);
}
@Override
protected Map<String, Integer> makePopulatedMap() {
Table<Character, String, Integer> table = HashBasedTable.create();
table.put('a', "one", 2);
table.put('a', "two", 4);
table.put('a', "three", 6);
table.put('b', "four", 8);
return transformValues(table, TableCollectionTest.DIVIDE_BY_2).row('a');
}
}
| TablesTransformValuesRowTest |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/type/UnknownTypeHandler.java | {
"start": 1277,
"end": 5733
} | class
____ final Configuration config;
private final Supplier<TypeHandlerRegistry> typeHandlerRegistrySupplier;
/**
* The constructor that pass a MyBatis configuration.
*
* @param configuration
* a MyBatis configuration
*
* @since 3.5.4
*/
public UnknownTypeHandler(Configuration configuration) {
this.config = configuration;
this.typeHandlerRegistrySupplier = configuration::getTypeHandlerRegistry;
}
/**
* The constructor that pass the type handler registry.
*
* @param typeHandlerRegistry
* a type handler registry
*
* @deprecated Since 3.5.4, please use the {@link #UnknownTypeHandler(Configuration)}.
*/
@Deprecated
public UnknownTypeHandler(TypeHandlerRegistry typeHandlerRegistry) {
this.config = new Configuration();
this.typeHandlerRegistrySupplier = () -> typeHandlerRegistry;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
throws SQLException {
TypeHandler handler = resolveTypeHandler(parameter, jdbcType);
handler.setParameter(ps, i, parameter, jdbcType);
}
@Override
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
TypeHandler<?> handler = resolveTypeHandler(rs, columnName);
return handler.getResult(rs, columnName);
}
@Override
public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
TypeHandler<?> handler = resolveTypeHandler(rs.getMetaData(), columnIndex);
if (handler == null || handler instanceof UnknownTypeHandler) {
handler = ObjectTypeHandler.INSTANCE;
}
return handler.getResult(rs, columnIndex);
}
@Override
public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getObject(columnIndex);
}
private TypeHandler<?> resolveTypeHandler(Object parameter, JdbcType jdbcType) {
TypeHandler<?> handler;
if (parameter == null) {
handler = ObjectTypeHandler.INSTANCE;
} else {
handler = typeHandlerRegistrySupplier.get().getTypeHandler(parameter.getClass(), jdbcType);
// check if handler is null (issue #270)
if (handler == null || handler instanceof UnknownTypeHandler) {
handler = ObjectTypeHandler.INSTANCE;
}
}
return handler;
}
private TypeHandler<?> resolveTypeHandler(ResultSet rs, String column) {
try {
Map<String, Integer> columnIndexLookup;
columnIndexLookup = new HashMap<>();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
boolean useColumnLabel = config.isUseColumnLabel();
for (int i = 1; i <= count; i++) {
String name = useColumnLabel ? rsmd.getColumnLabel(i) : rsmd.getColumnName(i);
columnIndexLookup.put(name, i);
}
Integer columnIndex = columnIndexLookup.get(column);
TypeHandler<?> handler = null;
if (columnIndex != null) {
handler = resolveTypeHandler(rsmd, columnIndex);
}
if (handler == null || handler instanceof UnknownTypeHandler) {
handler = ObjectTypeHandler.INSTANCE;
}
return handler;
} catch (SQLException e) {
throw new TypeException("Error determining JDBC type for column " + column + ". Cause: " + e, e);
}
}
private TypeHandler<?> resolveTypeHandler(ResultSetMetaData rsmd, Integer columnIndex) {
TypeHandler<?> handler = null;
JdbcType jdbcType = safeGetJdbcTypeForColumn(rsmd, columnIndex);
Class<?> javaType = safeGetClassForColumn(rsmd, columnIndex);
if (javaType != null && jdbcType != null) {
handler = typeHandlerRegistrySupplier.get().getTypeHandler(javaType, jdbcType);
} else if (javaType != null) {
handler = typeHandlerRegistrySupplier.get().getTypeHandler(javaType);
} else if (jdbcType != null) {
handler = typeHandlerRegistrySupplier.get().getTypeHandler(jdbcType);
}
return handler;
}
private JdbcType safeGetJdbcTypeForColumn(ResultSetMetaData rsmd, Integer columnIndex) {
try {
return JdbcType.forCode(rsmd.getColumnType(columnIndex));
} catch (Exception e) {
return null;
}
}
private Class<?> safeGetClassForColumn(ResultSetMetaData rsmd, Integer columnIndex) {
try {
return Resources.classForName(rsmd.getColumnClassName(columnIndex));
} catch (Exception e) {
return null;
}
}
}
| private |
java | quarkusio__quarkus | extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/security/BasicAuthenticationMechanism.java | {
"start": 1747,
"end": 7395
} | class ____ implements HttpAuthenticationMechanism {
private static final Logger log = Logger.getLogger(BasicAuthenticationMechanism.class);
private final String challenge;
private static final String BASIC = "basic";
private static final String BASIC_PREFIX = BASIC + " ";
private static final String LOWERCASE_BASIC_PREFIX = BASIC_PREFIX.toLowerCase(Locale.ENGLISH);
private static final int PREFIX_LENGTH = BASIC_PREFIX.length();
private static final String COLON = ":";
/**
* If silent is true then this mechanism will only take effect if there is an Authorization header.
* <p>
* This allows you to combine basic auth with form auth, so human users will use form based auth, but allows
* programmatic clients to login using basic auth.
*/
private final boolean silent;
private final Charset charset;
private final Map<Pattern, Charset> userAgentCharsets;
/**
* @deprecated use {@link BasicAuthenticationMechanism(String, boolean)}
*/
@Deprecated(forRemoval = true, since = "3.25")
public BasicAuthenticationMechanism(final String realmName) {
this(realmName, false);
}
public BasicAuthenticationMechanism(final String realmName, final boolean silent) {
this(realmName, silent, StandardCharsets.UTF_8, Collections.emptyMap());
}
public BasicAuthenticationMechanism(final String realmName, final boolean silent,
Charset charset, Map<Pattern, Charset> userAgentCharsets) {
this.challenge = realmName == null ? BASIC : BASIC_PREFIX + "realm=\"" + realmName + "\"";
this.silent = silent;
this.charset = charset;
this.userAgentCharsets = Map.copyOf(userAgentCharsets);
}
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
IdentityProviderManager identityProviderManager) {
List<String> authHeaders = context.request().headers().getAll(HttpHeaderNames.AUTHORIZATION);
if (authHeaders != null) {
for (String current : authHeaders) {
if (current.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) {
String base64Challenge = current.substring(PREFIX_LENGTH);
String plainChallenge = null;
byte[] decode = Base64.getDecoder().decode(base64Challenge);
Charset charset = this.charset;
if (!userAgentCharsets.isEmpty()) {
String ua = context.request().headers().get(HttpHeaderNames.USER_AGENT);
if (ua != null) {
for (Map.Entry<Pattern, Charset> entry : userAgentCharsets.entrySet()) {
if (entry.getKey().matcher(ua).find()) {
charset = entry.getValue();
break;
}
}
}
}
plainChallenge = new String(decode, charset);
int colonPos;
if ((colonPos = plainChallenge.indexOf(COLON)) > -1) {
String userName = plainChallenge.substring(0, colonPos);
char[] password = plainChallenge.substring(colonPos + 1).toCharArray();
log.debugf("Found basic auth header %s:***** (decoded using charset %s)", userName, charset);
UsernamePasswordAuthenticationRequest credential = new UsernamePasswordAuthenticationRequest(userName,
new PasswordCredential(password));
HttpSecurityUtils.setRoutingContextAttribute(credential, context);
context.put(HttpAuthenticationMechanism.class.getName(), this);
return identityProviderManager.authenticate(credential);
}
// By this point we had a header we should have been able to verify but for some reason
// it was not correctly structured.
return Uni.createFrom().failure(new AuthenticationFailedException());
}
}
}
// No suitable header has been found in this request,
return Uni.createFrom().optional(Optional.empty());
}
@Override
public Uni<ChallengeData> getChallenge(RoutingContext context) {
if (silent) {
//if this is silent we only send a challenge if the request contained auth headers
//otherwise we assume another method will send the challenge
String authHeader = context.request().headers().get(HttpHeaderNames.AUTHORIZATION);
if (authHeader == null) {
return Uni.createFrom().optional(Optional.empty());
}
}
ChallengeData result = new ChallengeData(
HttpResponseStatus.UNAUTHORIZED.code(),
HttpHeaderNames.WWW_AUTHENTICATE,
challenge);
return Uni.createFrom().item(result);
}
@Override
public Set<Class<? extends AuthenticationRequest>> getCredentialTypes() {
return Collections.singleton(UsernamePasswordAuthenticationRequest.class);
}
@Override
public Uni<HttpCredentialTransport> getCredentialTransport(RoutingContext context) {
return Uni.createFrom().item(new HttpCredentialTransport(HttpCredentialTransport.Type.AUTHORIZATION, BASIC));
}
@Override
public int getPriority() {
return 2000;
}
}
| BasicAuthenticationMechanism |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/search/SearchRequestAttributesExtractor.java | {
"start": 2090,
"end": 2402
} | class ____ to extract metrics attributes, it should do its best
* to extract the minimum set of needed information without hurting performance, and without
* ever breaking: if something goes wrong around extracting attributes, it should skip extracting
* them as opposed to failing the search.
*/
public final | is |
java | greenrobot__greendao | tests/DaoTest/src/androidTest/java/org/greenrobot/greendao/daotest/query/DeleteQueryTest.java | {
"start": 1253,
"end": 4559
} | class ____ extends TestEntityTestBase {
@Override
protected void setUp() throws Exception {
super.setUp();
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
}
public void testDeleteQuerySimple() {
ArrayList<TestEntity> inserted = insert(3);
int value = getSimpleInteger(1);
inserted.get(2).setSimpleInteger(value);
dao.update(inserted.get(2));
DeleteQuery<TestEntity> deleteQuery = dao.queryBuilder().where(Properties.SimpleInteger.eq(value))
.buildDelete();
deleteQuery.executeDeleteWithoutDetachingEntities();
List<TestEntity> allAfterDelete = dao.loadAll();
assertEquals(1, allAfterDelete.size());
assertEquals(getSimpleInteger(0), (int) allAfterDelete.get(0).getSimpleInteger());
}
public void testDeleteQueryOr() {
ArrayList<TestEntity> inserted = insert(3);
QueryBuilder<TestEntity> queryBuilder = dao.queryBuilder();
Integer value1 = inserted.get(0).getSimpleInteger();
Integer value2 = inserted.get(2).getSimpleInteger();
queryBuilder.whereOr(Properties.SimpleInteger.eq(value1), Properties.SimpleInteger.eq(value2));
DeleteQuery<TestEntity> deleteQuery = queryBuilder.buildDelete();
deleteQuery.executeDeleteWithoutDetachingEntities();
List<TestEntity> allAfterDelete = dao.loadAll();
assertEquals(1, allAfterDelete.size());
assertEquals(inserted.get(1).getSimpleInteger(), allAfterDelete.get(0).getSimpleInteger());
}
public void testDeleteQueryExecutingMultipleTimes() {
insert(3);
String value = getSimpleString(1);
DeleteQuery<TestEntity> deleteQuery = dao.queryBuilder().where(Properties.SimpleString.eq(value)).buildDelete();
deleteQuery.executeDeleteWithoutDetachingEntities();
assertEquals(2, dao.count());
deleteQuery.executeDeleteWithoutDetachingEntities();
assertEquals(2, dao.count());
insert(3);
assertEquals(5, dao.count());
deleteQuery.executeDeleteWithoutDetachingEntities();
assertEquals(4, dao.count());
}
public void testDeleteQueryChangeParameter() {
insert(3);
String value = getSimpleString(1);
DeleteQuery<TestEntity> deleteQuery = dao.queryBuilder().where(Properties.SimpleString.eq(value)).buildDelete();
deleteQuery.executeDeleteWithoutDetachingEntities();
assertEquals(2, dao.count());
deleteQuery.setParameter(0, getSimpleString(0));
deleteQuery.executeDeleteWithoutDetachingEntities();
assertEquals(1, dao.count());
TestEntity remaining = dao.loadAll().get(0);
assertEquals(getSimpleString(2), remaining.getSimpleString());
}
public void testBuildQueryAndDeleteQuery() {
insert(3);
int value = getSimpleInteger(1);
QueryBuilder<TestEntity> builder = dao.queryBuilder().where(Properties.SimpleInteger.eq(value));
Query<TestEntity> query = builder.build();
DeleteQuery<TestEntity> deleteQuery = builder.buildDelete();
assertEquals(1, query.list().size());
deleteQuery.executeDeleteWithoutDetachingEntities();
assertEquals(0, query.list().size());
}
}
| DeleteQueryTest |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/builder/multiple/builder/Case.java | {
"start": 1182,
"end": 1613
} | class ____ {
private String name;
private String builderCreationMethod;
protected Builder(String builderCreationMethod) {
this.builderCreationMethod = builderCreationMethod;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Case create() {
return new Case( this, "create" );
}
}
}
| Builder |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/client/RMDelegationTokenIdentifier.java | {
"start": 2621,
"end": 6485
} | class ____ extends TokenRenewer {
@Override
public boolean handleKind(Text kind) {
return KIND_NAME.equals(kind);
}
@Override
public boolean isManaged(Token<?> token) throws IOException {
return true;
}
private static
AbstractDelegationTokenSecretManager<RMDelegationTokenIdentifier> localSecretManager;
private static InetSocketAddress localServiceAddress;
@Private
public static void setSecretManager(
AbstractDelegationTokenSecretManager<RMDelegationTokenIdentifier> secretManager,
InetSocketAddress serviceAddress) {
localSecretManager = secretManager;
localServiceAddress = serviceAddress;
}
@SuppressWarnings("unchecked")
@Override
public long renew(Token<?> token, Configuration conf) throws IOException,
InterruptedException {
final ApplicationClientProtocol rmClient = getRmClient(token, conf);
if (rmClient != null) {
try {
RenewDelegationTokenRequest request =
Records.newRecord(RenewDelegationTokenRequest.class);
request.setDelegationToken(convertToProtoToken(token));
return rmClient.renewDelegationToken(request).getNextExpirationTime();
} catch (YarnException e) {
throw new IOException(e);
} finally {
RPC.stopProxy(rmClient);
}
} else {
return localSecretManager.renewToken(
(Token<RMDelegationTokenIdentifier>)token, getRenewer(token));
}
}
@SuppressWarnings("unchecked")
@Override
public void cancel(Token<?> token, Configuration conf) throws IOException,
InterruptedException {
final ApplicationClientProtocol rmClient = getRmClient(token, conf);
if (rmClient != null) {
try {
CancelDelegationTokenRequest request =
Records.newRecord(CancelDelegationTokenRequest.class);
request.setDelegationToken(convertToProtoToken(token));
rmClient.cancelDelegationToken(request);
} catch (YarnException e) {
throw new IOException(e);
} finally {
RPC.stopProxy(rmClient);
}
} else {
localSecretManager.cancelToken(
(Token<RMDelegationTokenIdentifier>)token, getRenewer(token));
}
}
private static ApplicationClientProtocol getRmClient(Token<?> token,
Configuration conf) throws IOException {
String[] services = token.getService().toString().split(",");
for (String service : services) {
InetSocketAddress addr = NetUtils.createSocketAddr(service);
if (localSecretManager != null && localServiceAddress != null) {
// return null if it's our token
InetAddress localServiceAddr = localServiceAddress.getAddress();
if (localServiceAddr != null && localServiceAddr.isAnyLocalAddress()) {
if (NetUtils.isLocalAddress(addr.getAddress()) &&
addr.getPort() == localServiceAddress.getPort()) {
return null;
}
} else if (addr.equals(localServiceAddress)) {
return null;
}
}
}
return ClientRMProxy.createRMProxy(conf, ApplicationClientProtocol.class);
}
// get renewer so we can always renew our own tokens
@SuppressWarnings("unchecked")
private static String getRenewer(Token<?> token) throws IOException {
return ((Token<RMDelegationTokenIdentifier>)token).decodeIdentifier()
.getRenewer().toString();
}
private static org.apache.hadoop.yarn.api.records.Token
convertToProtoToken(Token<?> token) {
return org.apache.hadoop.yarn.api.records.Token.newInstance(
token.getIdentifier(), token.getKind().toString(), token.getPassword(),
token.getService().toString());
}
}
}
| Renewer |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/converter/FSConfigToCSConfigConverterMain.java | {
"start": 1105,
"end": 1169
} | class ____ invokes the FS->CS converter.
*
*/
public final | that |
java | apache__camel | components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzNameCollisionTest.java | {
"start": 1530,
"end": 6688
} | class ____ {
private DefaultCamelContext camel1;
private DefaultCamelContext camel2;
@Test
public void testDupeName() throws Exception {
camel1 = new DefaultCamelContext();
camel1.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("quartz://myGroup/myTimerName?cron=0/1+*+*+*+*+?").to("log:one", "mock:one");
}
});
camel1.start();
RouteBuilder routeBuilder = new RouteBuilder() {
@Override
public void configure() {
from("quartz://myGroup/myTimerName?cron=0/2+*+*+*+*+?").to("log:two", "mock:two");
}
};
Exception ex = assertThrows(FailedToCreateRouteException.class, () -> camel1.addRoutes(routeBuilder));
String reason = ex.getMessage();
assertTrue(reason.contains("Trigger key myGroup.myTimerName is already in use"));
}
@Test
public void testDupeNameMultiContext() throws Exception {
camel1 = new DefaultCamelContext();
camel1.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("quartz://myGroup/myTimerName?cron=0/1+*+*+*+*+?").to("log:one", "mock:one");
}
});
camel1.start();
camel2 = new DefaultCamelContext();
camel2.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("quartz://myGroup/myTimerName=0/2+*+*+*+*+?").to("log:two", "mock:two");
}
});
assertDoesNotThrow(() -> camel2.start());
}
/**
* Don't check for a name collision if the job is stateful.
*/
@Test
public void testNoStatefulCollisionError() throws Exception {
camel1 = new DefaultCamelContext();
camel1.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("quartz://myGroup/myTimerName?stateful=true&cron=0/1+*+*+*+*+?").to("log:one", "mock:one");
}
});
camel1.start();
camel2 = new DefaultCamelContext();
camel2.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("quartz://myGroup/myTimerName?stateful=true").to("log:two", "mock:two");
}
});
// if no exception is thrown then this test passed.
assertDoesNotThrow(() -> camel2.start());
}
/**
* Make sure a resume doesn't trigger a dupe name error.
*/
@Test
public void testRestart() throws Exception {
DefaultCamelContext camel = new DefaultCamelContext();
camel.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("quartz://myGroup/myTimerName?cron=0/1+*+*+*+*+?").to("log:one", "mock:one");
}
});
// traverse a litany of states
assertDoesNotThrow(camel::start, "Start should have not thrown exception");
Thread.sleep(100);
assertDoesNotThrow(camel::suspend, "Suspend should not have thrown exception");
Thread.sleep(100);
assertDoesNotThrow(camel::resume, "Resume should not have thrown exception");
Thread.sleep(100);
assertDoesNotThrow(camel::stop, "Stop should not have thrown exception");
Thread.sleep(100);
assertDoesNotThrow(camel::start, "Start again should have thrown exception");
Thread.sleep(100);
assertDoesNotThrow(camel::stop, "Final stop should have thrown exception");
}
/**
* Confirm the quartz trigger is removed on route stop.
*/
@Test
public void testRemoveJob() throws Exception {
camel1 = new DefaultCamelContext();
camel1.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("quartz://myGroup/myTimerName?cron=0/1+*+*+*+*+?").id("route-1").to("log:one", "mock:one");
}
});
camel1.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("quartz://myGroup2/myTimerName?cron=0/1+*+*+*+*+?").id("route-2").to("log:one", "mock:one");
}
});
camel1.start();
QuartzComponent component = (QuartzComponent) camel1.getComponent("quartz");
Scheduler scheduler = component.getScheduler();
TriggerKey triggerKey = TriggerKey.triggerKey("myTimerName", "myGroup");
Trigger trigger = scheduler.getTrigger(triggerKey);
assertNotNull(trigger);
camel1.getRouteController().stopRoute("route-1");
Trigger.TriggerState triggerState = component.getScheduler().getTriggerState(triggerKey);
assertNotNull(trigger);
assertEquals(Trigger.TriggerState.PAUSED, triggerState);
}
@AfterEach
public void cleanUp() {
if (camel1 != null) {
camel1.stop();
camel1 = null;
}
if (camel2 != null) {
camel2.stop();
camel2 = null;
}
}
}
| QuartzNameCollisionTest |
java | micronaut-projects__micronaut-core | http-server-netty/src/main/java/io/micronaut/http/server/netty/NettyEmbeddedServer.java | {
"start": 1327,
"end": 2880
} | interface ____
extends EmbeddedServer,
WebSocketSessionRepository,
ChannelPipelineCustomizer,
RefreshEventListener,
NettyServerCustomizer.Registry,
GracefulShutdownCapable {
/**
* Gets the set of all ports this Netty server is bound to.
* @return An immutable set of bound ports if the server has been started with {@link #start()} an empty set otherwise.
*/
default Set<Integer> getBoundPorts() {
return Collections.singleton(getPort());
}
@Override
@NonNull
default NettyEmbeddedServer start() {
return (NettyEmbeddedServer) EmbeddedServer.super.start();
}
@Override
@NonNull
default NettyEmbeddedServer stop() {
return (NettyEmbeddedServer) EmbeddedServer.super.stop();
}
/**
* Stops the Netty instance, but keeps the ApplicationContext running.
* This for CRaC checkpointing purposes.
* This method will only return after waiting for netty to stop.
*
* @return The stopped NettyEmbeddedServer
*/
@SuppressWarnings("unused") // Used by CRaC
@NonNull
NettyEmbeddedServer stopServerOnly();
@Override
default void register(@NonNull NettyServerCustomizer customizer) {
throw new UnsupportedOperationException();
}
@Override
default CompletionStage<?> shutdownGracefully() {
// default implementation for compatibility
return CompletableFuture.completedStage(null);
}
}
| NettyEmbeddedServer |
java | netty__netty | codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Exception.java | {
"start": 13524,
"end": 14227
} | class ____ extends Http2Exception {
private static final long serialVersionUID = 1077888485687219443L;
StacklessHttp2Exception(Http2Error error, String message, ShutdownHint shutdownHint) {
super(error, message, shutdownHint);
}
StacklessHttp2Exception(Http2Error error, String message, ShutdownHint shutdownHint, boolean shared) {
super(error, message, shutdownHint, shared);
}
// Override fillInStackTrace() so we not populate the backtrace via a native call and so leak the
// Classloader.
@Override
public Throwable fillInStackTrace() {
return this;
}
}
}
| StacklessHttp2Exception |
java | google__guava | android/guava/src/com/google/common/collect/TreeBasedTable.java | {
"start": 3302,
"end": 3454
} | class ____<R, C, V> extends StandardRowSortedTable<R, C, V> {
private final Comparator<? super C> columnComparator;
private static final | TreeBasedTable |
java | quarkusio__quarkus | extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/reactive/ReactiveMongoCollection.java | {
"start": 21006,
"end": 21813
} | class ____ decode each document into
* @param <D> the target document type of the iterable.
* @param options the stream options
* @return the stream of changes
*/
<D> Multi<ChangeStreamDocument<D>> watch(Class<D> clazz,
ChangeStreamOptions options);
/**
* Creates a change stream for this collection.
*
* @param pipeline the aggregation pipeline to apply to the change stream
* @param options the stream options
* @return the stream of changes
*/
Multi<ChangeStreamDocument<Document>> watch(List<? extends Bson> pipeline,
ChangeStreamOptions options);
/**
* Creates a change stream for this collection.
*
* @param pipeline the aggregation pipeline to apply to the change stream
* @param clazz the | to |
java | netty__netty | codec-base/src/main/java/io/netty/handler/codec/ReplayingDecoder.java | {
"start": 4212,
"end": 5013
} | class ____ extends {@link ReplayingDecoder}<{@link Void}> {
*
* private final Queue<Integer> values = new LinkedList<Integer>();
*
* {@code @Override}
* public void decode(.., {@link ByteBuf} buf, List<Object> out) throws Exception {
*
* // A message contains 2 integers.
* values.offer(buf.readInt());
* values.offer(buf.readInt());
*
* // This assertion will fail intermittently since values.offer()
* // can be called more than two times!
* assert values.size() == 2;
* out.add(values.poll() + values.poll());
* }
* }</pre>
* The correct implementation looks like the following, and you can also
* utilize the 'checkpoint' feature which is explained in detail in the
* next section.
* <pre> public | MyDecoder |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/internal/EntityRepresentationStrategyPojoStandard.java | {
"start": 5028,
"end": 8850
} | class ____ abstract, but the hierarchy always gets entities loaded/proxied using their concrete type.
// So we do not need proxies for this entity class.
return null;
}
else if ( entityPersister.getBytecodeEnhancementMetadata().isEnhancedForLazyLoading()
&& bootDescriptor.getRootClass() == bootDescriptor
&& !bootDescriptor.hasSubclasses() ) {
// the entity is bytecode enhanced for lazy loading
// and is not part of an inheritance hierarchy,
// so no need for a ProxyFactory
return null;
}
else {
if ( proxyJavaType != null && entityPersister.isLazy() ) {
final var proxyFactory = createProxyFactory( bootDescriptor, bytecodeProvider, creationContext );
if ( proxyFactory == null ) {
((EntityMetamodel) entityPersister).setLazy( false );
}
return proxyFactory;
}
else {
return null;
}
}
}
private Map<String, PropertyAccess> buildPropertyAccessMap(PersistentClass bootDescriptor) {
final Map<String, PropertyAccess> propertyAccessMap = new LinkedHashMap<>();
for ( var property : bootDescriptor.getPropertyClosure() ) {
propertyAccessMap.put( property.getName(), makePropertyAccess( property ) );
}
return propertyAccessMap;
}
/*
* Used by Hibernate Reactive
*/
protected EntityInstantiator determineInstantiator(PersistentClass bootDescriptor, EntityPersister persister) {
if ( reflectionOptimizer != null && reflectionOptimizer.getInstantiationOptimizer() != null ) {
return new EntityInstantiatorPojoOptimized(
persister,
bootDescriptor,
mappedJtd,
reflectionOptimizer.getInstantiationOptimizer()
);
}
else {
return new EntityInstantiatorPojoStandard( persister, bootDescriptor, mappedJtd );
}
}
private ProxyFactory createProxyFactory(
PersistentClass bootDescriptor,
BytecodeProvider bytecodeProvider,
RuntimeModelCreationContext creationContext) {
final var mappedClass = mappedJtd.getJavaTypeClass();
final var proxyInterface = proxyJtd == null ? null : proxyJtd.getJavaTypeClass();
final var proxyInterfaces = proxyInterfaces( bootDescriptor, proxyInterface, mappedClass );
final var clazz = bootDescriptor.getMappedClass();
final Method idGetterMethod;
final Method idSetterMethod;
try {
for ( var property : bootDescriptor.getProperties() ) {
validateGetterSetterMethodProxyability( "Getter",
property.getGetter( clazz ).getMethod() );
validateGetterSetterMethodProxyability( "Setter",
property.getSetter( clazz ).getMethod() );
}
if ( identifierPropertyAccess != null ) {
idGetterMethod = identifierPropertyAccess.getGetter().getMethod();
idSetterMethod = identifierPropertyAccess.getSetter().getMethod();
validateGetterSetterMethodProxyability( "Getter", idGetterMethod );
validateGetterSetterMethodProxyability( "Setter", idSetterMethod );
}
else {
idGetterMethod = null;
idSetterMethod = null;
}
}
catch (HibernateException he) {
CORE_LOGGER.unableToCreateProxyFactory( clazz.getName(), he );
return null;
}
final var proxyGetIdentifierMethod =
idGetterMethod == null || proxyInterface == null ? null
: getMethod( proxyInterface, idGetterMethod );
final var proxySetIdentifierMethod =
idSetterMethod == null || proxyInterface == null ? null
: getMethod( proxyInterface, idSetterMethod );
return instantiateProxyFactory(
bootDescriptor,
bytecodeProvider,
creationContext,
proxyGetIdentifierMethod,
proxySetIdentifierMethod,
mappedClass,
proxyInterfaces
);
}
private static Set<Class<?>> proxyInterfaces(
PersistentClass bootDescriptor,
Class<?> proxyInterface,
Class<?> mappedClass) {
// HHH-17578 - We need to preserve the order of the interfaces to ensure
// that the most general @Proxy declared | is |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/FindIdentifiersTest.java | {
"start": 11308,
"end": 11777
} | class ____ {
private String s1;
private static String s2;
// BUG: Diagnostic contains: [s2]
private static Runnable r = () -> String.format(s2);
}
""")
.doTest();
}
@Test
public void findAllIdentsStaticLambdaWithLocalClass() {
CompilationTestHelper.newInstance(PrintIdents.class, getClass())
.addSourceLines(
"Test.java",
"""
| Test |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ProtoBuilderReturnValueIgnoredTest.java | {
"start": 3352,
"end": 3717
} | class ____ {
private void singleField(Duration.Builder proto) {
proto.build();
}
}
""")
.addOutputLines(
"Test.java",
"""
import static com.google.common.base.Preconditions.checkState;
import com.google.protobuf.Duration;
final | Test |
java | apache__camel | core/camel-core-xml/src/main/java/org/apache/camel/core/xml/CamelStreamCachingStrategyDefinition.java | {
"start": 4173,
"end": 8843
} | class ____ can be separated by comma.
*/
public void setDenyClasses(String denyClasses) {
this.denyClasses = denyClasses;
}
public String getSpoolEnabled() {
return spoolEnabled;
}
/**
* To enable stream caching spooling to disk. This means, for large stream messages (over 128 KB by default) will be
* cached in a temporary file instead, and Camel will handle deleting the temporary file once the cached stream is
* no longer necessary.
*
* Default is false.
*/
public void setSpoolEnabled(String spoolEnabled) {
this.spoolEnabled = spoolEnabled;
}
public String getSpoolDirectory() {
return spoolDirectory;
}
/**
* Sets the spool (temporary) directory to use for overflow and spooling to disk.
* <p/>
* If no spool directory has been explicit configured, then a temporary directory is created in the
* <tt>java.io.tmpdir</tt> directory.
*/
public void setSpoolDirectory(String spoolDirectory) {
this.spoolDirectory = spoolDirectory;
}
public String getSpoolCipher() {
return spoolCipher;
}
/**
* Sets a cipher name to use when spooling to disk to write with encryption.
* <p/>
* By default the data is not encrypted.
*/
public void setSpoolCipher(String spoolCipher) {
this.spoolCipher = spoolCipher;
}
public String getSpoolThreshold() {
return spoolThreshold;
}
/**
* Threshold in bytes when overflow to disk is activated.
* <p/>
* The default threshold is {@link org.apache.camel.StreamCache#DEFAULT_SPOOL_THRESHOLD} bytes (eg 128kb). Use
* <tt>-1</tt> to disable overflow to disk.
*/
public void setSpoolThreshold(String spoolThreshold) {
this.spoolThreshold = spoolThreshold;
}
public String getSpoolUsedHeapMemoryThreshold() {
return spoolUsedHeapMemoryThreshold;
}
/**
* Sets a percentage (1-99) of used heap memory threshold to activate spooling to disk.
*/
public void setSpoolUsedHeapMemoryThreshold(String spoolUsedHeapMemoryThreshold) {
this.spoolUsedHeapMemoryThreshold = spoolUsedHeapMemoryThreshold;
}
public String getSpoolUsedHeapMemoryLimit() {
return spoolUsedHeapMemoryLimit;
}
/**
* Sets what the upper bounds should be when spoolUsedHeapMemoryThreshold is in use.
*/
public void setSpoolUsedHeapMemoryLimit(String spoolUsedHeapMemoryLimit) {
this.spoolUsedHeapMemoryLimit = spoolUsedHeapMemoryLimit;
}
public String getSpoolRules() {
return spoolRules;
}
/**
* Reference to one or more custom {@link org.apache.camel.spi.StreamCachingStrategy.SpoolRule} to use. Multiple
* rules can be separated by comma.
*/
public void setSpoolRules(String spoolRules) {
this.spoolRules = spoolRules;
}
public String getBufferSize() {
return bufferSize;
}
/**
* Sets the buffer size to use when allocating in-memory buffers used for in-memory stream caches.
* <p/>
* The default size is {@link org.apache.camel.util.IOHelper#DEFAULT_BUFFER_SIZE}
*/
public void setBufferSize(String bufferSize) {
this.bufferSize = bufferSize;
}
public String getRemoveSpoolDirectoryWhenStopping() {
return removeSpoolDirectoryWhenStopping;
}
/**
* Whether to remove the temporary directory when stopping.
* <p/>
* This option is default <tt>true</tt>
*/
public void setRemoveSpoolDirectoryWhenStopping(String removeSpoolDirectoryWhenStopping) {
this.removeSpoolDirectoryWhenStopping = removeSpoolDirectoryWhenStopping;
}
public String getStatisticsEnabled() {
return statisticsEnabled;
}
/**
* Sets whether statistics is enabled.
*/
public void setStatisticsEnabled(String statisticsEnabled) {
this.statisticsEnabled = statisticsEnabled;
}
public String getAnySpoolRules() {
return anySpoolRules;
}
/**
* Sets whether if just any of the {@link org.apache.camel.spi.StreamCachingStrategy.SpoolRule} rules returns
* <tt>true</tt> then shouldSpoolCache(long) returns <tt>true</tt>. If this option is <tt>false</tt>, then
* <b>all</b> the {@link org.apache.camel.spi.StreamCachingStrategy.SpoolRule} must return <tt>true</tt>.
* <p/>
* The default value is <tt>false</tt> which means that all the rules must return <tt>true</tt>.
*/
public void setAnySpoolRules(String anySpoolRules) {
this.anySpoolRules = anySpoolRules;
}
}
| names |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/api/DynamicContainerTests.java | {
"start": 1133,
"end": 3909
} | class ____ {
@Test
void appliesConfiguration() {
var child = dynamicTest("Test", Assertions::fail);
var container = dynamicContainer(config -> config //
.displayName("Container") //
.testSourceUri(URI.create("https://junit.org")) //
.executionMode(CONCURRENT) //
.childExecutionMode(SAME_THREAD) //
.children(child));
assertThat(container.getDisplayName()).isEqualTo("Container");
assertThat(container.getTestSourceUri()).contains(URI.create("https://junit.org"));
assertThat(container.getExecutionMode()).contains(CONCURRENT);
assertThat(container.getChildExecutionMode()).contains(SAME_THREAD);
assertThat(container.getChildren().map(DynamicNode.class::cast)).containsExactly(child);
}
@Test
void displayNameMustNotBeBlank() {
assertPreconditionViolationNotNullOrBlankFor("displayName", () -> dynamicContainer(__ -> {
}));
assertPreconditionViolationNotNullOrBlankFor("displayName",
() -> dynamicContainer(config -> config.displayName("")));
}
@SuppressWarnings("DataFlowIssue")
@Test
void executionModeMustNotBeNull() {
assertPreconditionViolationNotNullFor("executionMode",
() -> dynamicContainer(config -> config.executionMode(null)));
}
@SuppressWarnings("DataFlowIssue")
@Test
void childExecutionModeMustNotBeNull() {
assertPreconditionViolationNotNullFor("executionMode",
() -> dynamicContainer(config -> config.childExecutionMode(null)));
}
@SuppressWarnings("DataFlowIssue")
@Test
void childrenMustBeConfigured() {
assertPreconditionViolationNotNullFor("children",
() -> dynamicContainer(config -> config.children((DynamicNode[]) null)));
assertPreconditionViolationNotNullFor("children",
() -> dynamicContainer(config -> config.children((Stream<? extends DynamicNode>) null)));
assertPreconditionViolationNotNullFor("children",
() -> dynamicContainer(config -> config.children((Collection<? extends DynamicNode>) null)));
assertPreconditionViolationNotNullFor("children",
() -> dynamicContainer(config -> config.displayName("container")));
assertPreconditionViolationFor(() -> dynamicContainer(config -> config.children((DynamicNode) null))) //
.withMessage("children must not contain null elements");
}
@Test
void childrenMustNotBeConfiguredMoreThanOnce() {
assertPreconditionViolationFor(() -> dynamicContainer(config -> config.children().children())) //
.withMessage("children can only be set once");
assertPreconditionViolationFor(() -> dynamicContainer(config -> config.children().children(Stream.empty()))) //
.withMessage("children can only be set once");
assertPreconditionViolationFor(() -> dynamicContainer(config -> config.children().children(List.of()))) //
.withMessage("children can only be set once");
}
}
| DynamicContainerTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/hql/Reptile.java | {
"start": 267,
"end": 500
} | class ____ extends Animal {
private float bodyTemperature;
public float getBodyTemperature() {
return bodyTemperature;
}
public void setBodyTemperature(float bodyTemperature) {
this.bodyTemperature = bodyTemperature;
}
}
| Reptile |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/CockroachDialect.java | {
"start": 7265,
"end": 11816
} | class ____ extends Dialect {
// KNOWN LIMITATIONS:
// * no support for java.sql.Clob
// Pre-compile and reuse pattern
private static final Pattern CRDB_VERSION_PATTERN = Pattern.compile( "v[\\d]+(\\.[\\d]+)?(\\.[\\d]+)?" );
protected static final DatabaseVersion MINIMUM_VERSION = DatabaseVersion.make( 23, 1 );
protected final PostgreSQLDriverKind driverKind;
public CockroachDialect() {
this( MINIMUM_VERSION );
}
public CockroachDialect(DialectResolutionInfo info) {
this( fetchDataBaseVersion( info ), PostgreSQLDriverKind.determineKind( info ) );
registerKeywords( info );
}
public CockroachDialect(DialectResolutionInfo info, String versionString) {
this(
versionString == null
? info.makeCopyOrDefault( MINIMUM_VERSION )
: parseVersion( versionString ),
PostgreSQLDriverKind.determineKind( info )
);
registerKeywords( info );
}
public CockroachDialect(DatabaseVersion version) {
super(version);
driverKind = PostgreSQLDriverKind.PG_JDBC;
}
public CockroachDialect(DatabaseVersion version, PostgreSQLDriverKind driverKind) {
super(version);
this.driverKind = driverKind;
}
@Override
public DatabaseVersion determineDatabaseVersion(DialectResolutionInfo info) {
return fetchDataBaseVersion( info );
}
protected static DatabaseVersion fetchDataBaseVersion(DialectResolutionInfo info) {
String versionString = null;
final DatabaseMetaData databaseMetadata = info.getDatabaseMetadata();
if ( databaseMetadata != null ) {
try ( var statement = databaseMetadata.getConnection().createStatement() ) {
final ResultSet resultSet = statement.executeQuery( "SELECT version()" );
if ( resultSet.next() ) {
versionString = resultSet.getString( 1 );
}
}
catch (SQLException ex) {
// Ignore
}
}
if ( versionString == null ) {
// default to the dialect-specific configuration setting
versionString = ConfigurationHelper.getString( COCKROACH_VERSION_STRING, info.getConfigurationValues() );
}
return versionString != null ? parseVersion( versionString ) : info.makeCopyOrDefault( MINIMUM_VERSION );
}
public static DatabaseVersion parseVersion( String versionString ) {
DatabaseVersion databaseVersion = null;
// What the DB select returns is similar to "CockroachDB CCL v21.2.10 (x86_64-unknown-linux-gnu, built 2022/05/02 17:38:58, go1.16.6)"
final Matcher matcher = CRDB_VERSION_PATTERN.matcher( versionString == null ? "" : versionString );
if ( matcher.find() ) {
final String[] versionParts = StringHelper.split( ".", matcher.group().substring( 1 ) );
// if we got to this point, there is at least a major version, so no need to check [].length > 0
int majorVersion = parseInt( versionParts[0] );
int minorVersion = versionParts.length > 1 ? parseInt( versionParts[1] ) : 0;
int microVersion = versionParts.length > 2 ? parseInt( versionParts[2] ) : 0;
databaseVersion= new SimpleDatabaseVersion( majorVersion, minorVersion, microVersion);
}
if ( databaseVersion == null ) {
databaseVersion = MINIMUM_VERSION;
}
return databaseVersion;
}
@Override
protected DatabaseVersion getMinimumSupportedVersion() {
return MINIMUM_VERSION;
}
@Override
protected String columnType(int sqlTypeCode) {
return switch (sqlTypeCode) {
case TINYINT -> "smallint"; // no tinyint
case INTEGER -> "int4";
case NCHAR -> columnType( CHAR );
case NVARCHAR -> columnType( VARCHAR );
case NCLOB, CLOB -> "string";
case BINARY, VARBINARY, BLOB -> "bytes";
// We do not use the time with timezone type because PG
// deprecated it and it lacks certain operations like
// subtraction
// case TIME_UTC -> columnType( TIME_WITH_TIMEZONE );
case TIMESTAMP_UTC -> columnType( TIMESTAMP_WITH_TIMEZONE );
default -> super.columnType(sqlTypeCode);
};
}
@Override
protected String castType(int sqlTypeCode) {
return switch (sqlTypeCode) {
case CHAR, NCHAR, VARCHAR, NVARCHAR, LONG32VARCHAR, LONG32NVARCHAR -> "string";
case BINARY, VARBINARY, LONG32VARBINARY -> "bytes";
default -> super.castType( sqlTypeCode );
};
}
@Override
protected void registerColumnTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
super.registerColumnTypes( typeContributions, serviceRegistry );
final DdlTypeRegistry ddlTypeRegistry = typeContributions.getTypeConfiguration().getDdlTypeRegistry();
ddlTypeRegistry.addDescriptor( new DdlTypeImpl( UUID, "uuid", this ) );
// The following DDL types require that the PGobject | CockroachDialect |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/stats/outlierdetection/TimingStats.java | {
"start": 855,
"end": 2742
} | class ____ implements Writeable, ToXContentObject {
public static final ParseField ELAPSED_TIME = new ParseField("elapsed_time");
public static TimingStats fromXContent(XContentParser parser, boolean ignoreUnknownFields) {
return createParser(ignoreUnknownFields).apply(parser, null);
}
private static ConstructingObjectParser<TimingStats, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<TimingStats, Void> parser = new ConstructingObjectParser<>(
"outlier_detection_timing_stats",
ignoreUnknownFields,
a -> new TimingStats(TimeValue.timeValueMillis((long) a[0]))
);
parser.declareLong(ConstructingObjectParser.constructorArg(), ELAPSED_TIME);
return parser;
}
private final TimeValue elapsedTime;
public TimingStats(TimeValue elapsedTime) {
this.elapsedTime = Objects.requireNonNull(elapsedTime);
}
public TimingStats(StreamInput in) throws IOException {
this.elapsedTime = in.readTimeValue();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeTimeValue(elapsedTime);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.humanReadableField(ELAPSED_TIME.getPreferredName(), ELAPSED_TIME.getPreferredName() + "_string", elapsedTime);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TimingStats that = (TimingStats) o;
return Objects.equals(elapsedTime, that.elapsedTime);
}
@Override
public int hashCode() {
return Objects.hash(elapsedTime);
}
}
| TimingStats |
java | apache__flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/TypeInferenceExtractorTest.java | {
"start": 101134,
"end": 101369
} | class ____ implements Procedure {
public String[] call(Object procedureContext, byte... bytes) {
return null;
}
}
@ProcedureHint(output = @DataTypeHint("INT"))
private static | VarArgWithByteProcedure |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/ArgumentCount.java | {
"start": 1208,
"end": 1967
} | interface ____ {
/**
* Enables custom validation of argument counts after {@link #getMinCount()} and {@link
* #getMaxCount()} have been validated.
*
* @param count total number of arguments including each argument for a vararg function call
*/
boolean isValidCount(int count);
/**
* Returns the minimum number of argument (inclusive) that a function can take.
*
* <p>{@link Optional#empty()} if such a lower bound is not defined.
*/
Optional<Integer> getMinCount();
/**
* Returns the maximum number of argument (inclusive) that a function can take.
*
* <p>{@link Optional#empty()} if such an upper bound is not defined.
*/
Optional<Integer> getMaxCount();
}
| ArgumentCount |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/jdk/NumberSerTest.java | {
"start": 2977,
"end": 3332
} | class ____ extends ValueSerializer<BigDecimal> {
private final DecimalFormat df = createDecimalFormatForDefaultLocale("0.0");
@Override
public void serialize(BigDecimal value, JsonGenerator gen, SerializationContext serializers) {
gen.writeString(df.format(value));
}
}
static | BigDecimalAsStringSerializer |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/synonyms/SynonymsTestUtils.java | {
"start": 955,
"end": 2338
} | class ____ {
private SynonymsTestUtils() {
throw new UnsupportedOperationException();
}
public static SynonymRule[] randomSynonymsSet(int length) {
return randomSynonymsSet(length, length);
}
public static SynonymRule[] randomSynonymsSet(int minLength, int maxLength) {
return randomArray(minLength, maxLength, SynonymRule[]::new, SynonymsTestUtils::randomSynonymRule);
}
public static SynonymRule[] randomSynonymsSetWithoutIds(int minLength, int maxLength) {
return randomArray(minLength, maxLength, SynonymRule[]::new, () -> randomSynonymRule(null));
}
static SynonymRule[] randomSynonymsSet() {
return randomSynonymsSet(0, 10);
}
static SynonymSetSummary[] randomSynonymsSetSummary() {
return randomArray(10, SynonymSetSummary[]::new, SynonymsTestUtils::randomSynonymSetSummary);
}
static SynonymRule randomSynonymRule() {
return randomSynonymRule(randomBoolean() ? null : randomIdentifier());
}
public static SynonymRule randomSynonymRule(String id) {
return new SynonymRule(id, String.join(", ", randomArray(1, 10, String[]::new, () -> randomAlphaOfLengthBetween(1, 10))));
}
static SynonymSetSummary randomSynonymSetSummary() {
return new SynonymSetSummary(randomLongBetween(1, 10000), randomIdentifier());
}
}
| SynonymsTestUtils |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/filter/NullConversionsSkipTest.java | {
"start": 738,
"end": 891
} | class ____ {
public String nullsOk = "a";
@JsonSetter(nulls=Nulls.SKIP)
public String noNulls = "b";
}
static | NullSkipField |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java | {
"start": 29484,
"end": 29728
} | class ____ {
int a = foo(1);
private int foo(int a, int... b) {
return a;
}
}
""")
.addOutputLines(
"Test.java",
"""
| Test |
java | apache__camel | components/camel-flink/src/main/java/org/apache/camel/component/flink/annotations/AnnotatedDataSetCallback.java | {
"start": 1663,
"end": 1810
} | class ____ be
* maintained for backward compatibility but may be removed in future versions.
*/
@Deprecated(since = "4.16.0")
public | will |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/heuristic/NXYSignificanceHeuristic.java | {
"start": 4393,
"end": 4556
} | class
____.N_1 = subsetSize;
// all docs
frequencies.N = supersetSize;
} else {
// documents not in | frequencies |
java | apache__spark | sql/core/src/main/java/org/apache/spark/sql/execution/datasources/parquet/ParquetVectorUpdaterFactory.java | {
"start": 41674,
"end": 43581
} | class ____ implements ParquetVectorUpdater {
private final boolean failIfRebase;
private final ZoneId convertTz;
private final String timeZone;
BinaryToSQLTimestampConvertTzRebaseUpdater(
boolean failIfRebase,
ZoneId convertTz,
String timeZone) {
this.failIfRebase = failIfRebase;
this.convertTz = convertTz;
this.timeZone = timeZone;
}
@Override
public void readValues(
int total,
int offset,
WritableColumnVector values,
VectorizedValuesReader valuesReader) {
for (int i = 0; i < total; i++) {
readValue(offset + i, values, valuesReader);
}
}
@Override
public void skipValues(int total, VectorizedValuesReader valuesReader) {
valuesReader.skipFixedLenByteArray(total, 12);
}
@Override
public void readValue(
int offset,
WritableColumnVector values,
VectorizedValuesReader valuesReader) {
// Read 12 bytes for INT96
long julianMicros = ParquetRowConverter.binaryToSQLTimestamp(valuesReader.readBinary(12));
long gregorianMicros = rebaseInt96(julianMicros, failIfRebase, timeZone);
long adjTime = DateTimeUtils.convertTz(gregorianMicros, convertTz, UTC);
values.putLong(offset, adjTime);
}
@Override
public void decodeSingleDictionaryId(
int offset,
WritableColumnVector values,
WritableColumnVector dictionaryIds,
Dictionary dictionary) {
Binary v = dictionary.decodeToBinary(dictionaryIds.getDictId(offset));
long julianMicros = ParquetRowConverter.binaryToSQLTimestamp(v);
long gregorianMicros = rebaseInt96(julianMicros, failIfRebase, timeZone);
long adjTime = DateTimeUtils.convertTz(gregorianMicros, convertTz, UTC);
values.putLong(offset, adjTime);
}
}
private static | BinaryToSQLTimestampConvertTzRebaseUpdater |
java | apache__camel | test-infra/camel-test-infra-openldap/src/test/java/org/apache/camel/test/infra/openldap/services/OpenldapServiceFactory.java | {
"start": 1558,
"end": 1658
} | class ____ extends OpenldapRemoteInfraService implements OpenldapService {
}
}
| OpenldapRemoteService |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/Helpers.java | {
"start": 16807,
"end": 16997
} | class ____ extends NullsBefore {
public static final NullsBeforeB INSTANCE = new NullsBeforeB();
private NullsBeforeB() {
super("b");
}
}
public static final | NullsBeforeB |
java | quarkusio__quarkus | extensions/mailer/deployment/src/test/java/io/quarkus/mailer/NamedMailersTemplatesInjectionTest.java | {
"start": 5783,
"end": 6337
} | class ____ {
@Inject
@MailerName("client1")
MailTemplate test1;
@Location("mails/test2")
@MailerName("client1")
MailTemplate testMail;
Uni<Void> send1() {
return test1.to("quarkus-template-client1-send1@quarkus.io").subject("Test").data("name", "John").send();
}
Uni<Void> send2() {
return testMail.to("quarkus-template-client1-send2@quarkus.io").subject("Test").data("name", "Lu").send();
}
}
@Singleton
static | MailTemplatesNamedClient1 |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/MessageSource.java | {
"start": 7932,
"end": 9861
} | interface ____ {
/**
* The default message context.
*/
MessageContext DEFAULT = new MessageContext() { };
/**
* The locale to use to resolve messages.
* @return The locale
*/
@NonNull default Locale getLocale() {
return Locale.getDefault();
}
/**
* The locale to use to resolve messages.
* @param defaultLocale The locale to use if no locale is present
* @return The locale
*/
@NonNull default Locale getLocale(@Nullable Locale defaultLocale) {
return defaultLocale != null ? defaultLocale : getLocale();
}
/**
* @return The variables to use resolve message placeholders
*/
@NonNull default Map<String, Object> getVariables() {
return Collections.emptyMap();
}
/**
* Obtain a message context for the given locale.
* @param locale The locale
* @return The message context
*/
static @NonNull MessageContext of(@Nullable Locale locale) {
return new DefaultMessageContext(locale, null);
}
/**
* Obtain a message context for the given variables.
* @param variables The variables.
* @return The message context
*/
static @NonNull MessageContext of(@Nullable Map<String, Object> variables) {
return new DefaultMessageContext(null, variables);
}
/**
* Obtain a message context for the given locale and variables.
* @param locale The locale
* @param variables The variables.
* @return The message context
*/
static @NonNull MessageContext of(@Nullable Locale locale, @Nullable Map<String, Object> variables) {
return new DefaultMessageContext(locale, variables);
}
}
}
| MessageContext |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/apidiff/ApiDiffCheckerTest.java | {
"start": 19074,
"end": 19261
} | class ____ {
@RequiresNewApiVersion public static final int FOO = 1;
}
""")
.addSourceLines(
"Test.java",
"""
import my.lib.Lib;
| Lib |
java | grpc__grpc-java | stub/src/main/java/io/grpc/stub/AbstractBlockingStub.java | {
"start": 1140,
"end": 2549
} | class ____<S extends AbstractBlockingStub<S>>
extends AbstractStub<S> {
protected AbstractBlockingStub(Channel channel, CallOptions callOptions) {
super(channel, callOptions);
}
/**
* Returns a new blocking stub with the given channel for the provided method configurations.
*
* @since 1.26.0
* @param factory the factory to create a blocking stub
* @param channel the channel that this stub will use to do communications
*/
public static <T extends AbstractStub<T>> T newStub(
StubFactory<T> factory, Channel channel) {
return newStub(factory, channel, CallOptions.DEFAULT);
}
/**
* Returns a new blocking stub with the given channel for the provided method configurations.
*
* @since 1.26.0
* @param factory the factory to create a blocking stub
* @param channel the channel that this stub will use to do communications
* @param callOptions the runtime call options to be applied to every call on this stub
*/
public static <T extends AbstractStub<T>> T newStub(
StubFactory<T> factory, Channel channel, CallOptions callOptions) {
T stub = factory.newStub(
channel, callOptions.withOption(ClientCalls.STUB_TYPE_OPTION, StubType.BLOCKING));
assert stub instanceof AbstractBlockingStub
: String.format("Expected AbstractBlockingStub, but got %s.", stub.getClass());
return stub;
}
}
| AbstractBlockingStub |
java | elastic__elasticsearch | build-tools/src/main/java/org/elasticsearch/gradle/testclusters/TestClustersPlugin.java | {
"start": 2371,
"end": 9212
} | class ____ implements Plugin<Project> {
public static final Attribute<Boolean> BUNDLE_ATTRIBUTE = Attribute.of("bundle", Boolean.class);
public static final String EXTENSION_NAME = "testClusters";
public static final String THROTTLE_SERVICE_NAME = "testClustersThrottle";
private static final String LIST_TASK_NAME = "listTestClusters";
public static final String REGISTRY_SERVICE_NAME = "testClustersRegistry";
private static final Logger logger = Logging.getLogger(TestClustersPlugin.class);
public static final String TEST_CLUSTER_TASKS_SERVICE = "testClusterTasksService";
private final ProviderFactory providerFactory;
private Provider<File> runtimeJavaProvider;
private Function<Version, Boolean> isReleasedVersion = v -> true;
@Inject
protected FileSystemOperations getFileSystemOperations() {
throw new UnsupportedOperationException();
}
@Inject
protected ArchiveOperations getArchiveOperations() {
throw new UnsupportedOperationException();
}
@Inject
protected ExecOperations getExecOperations() {
throw new UnsupportedOperationException();
}
@Inject
protected FileOperations getFileOperations() {
throw new UnsupportedOperationException();
}
@Inject
public TestClustersPlugin(ProviderFactory providerFactory) {
this.providerFactory = providerFactory;
}
public void setRuntimeJava(Provider<File> runtimeJava) {
this.runtimeJavaProvider = runtimeJava;
}
public void setIsReleasedVersion(Function<Version, Boolean> isReleasedVersion) {
this.isReleasedVersion = isReleasedVersion;
}
@Override
public void apply(Project project) {
project.getPlugins().apply(DistributionDownloadPlugin.class);
project.getPlugins().apply(JvmToolchainsPlugin.class);
project.getRootProject().getPluginManager().apply(ReaperPlugin.class);
Provider<ReaperService> reaperServiceProvider = GradleUtils.getBuildService(
project.getGradle().getSharedServices(),
ReaperPlugin.REAPER_SERVICE_NAME
);
JavaToolchainService toolChainService = project.getExtensions().getByType(JavaToolchainService.class);
Provider<JavaLauncher> fallbackJdk17Launcher = toolChainService.launcherFor(spec -> {
spec.getVendor().set(JvmVendorSpec.ADOPTIUM);
spec.getLanguageVersion().set(JavaLanguageVersion.of(17));
});
runtimeJavaProvider = providerFactory.provider(
() -> System.getenv("RUNTIME_JAVA_HOME") == null ? Jvm.current().getJavaHome() : new File(System.getenv("RUNTIME_JAVA_HOME"))
);
// register cluster registry as a global build service
Provider<TestClustersRegistry> testClustersRegistryProvider = project.getGradle()
.getSharedServices()
.registerIfAbsent(REGISTRY_SERVICE_NAME, TestClustersRegistry.class, noop());
// enable the DSL to describe clusters
NamedDomainObjectContainer<ElasticsearchCluster> container = createTestClustersContainerExtension(
project,
testClustersRegistryProvider,
reaperServiceProvider,
fallbackJdk17Launcher
);
// provide a task to be able to list defined clusters.
createListClustersTask(project, container);
// register throttle so we only run at most max-workers/2 nodes concurrently
Provider<TestClustersThrottle> testClustersThrottleProvider = project.getGradle()
.getSharedServices()
.registerIfAbsent(
THROTTLE_SERVICE_NAME,
TestClustersThrottle.class,
spec -> spec.getMaxParallelUsages().set(Math.max(1, project.getGradle().getStartParameter().getMaxWorkerCount() / 2))
);
project.getTasks().withType(TestClustersAware.class).configureEach(task -> { task.usesService(testClustersThrottleProvider); });
project.getRootProject().getPluginManager().apply(TestClustersHookPlugin.class);
configureArtifactTransforms(project);
}
private void configureArtifactTransforms(Project project) {
project.getDependencies().getAttributesSchema().attribute(BUNDLE_ATTRIBUTE);
project.getDependencies().getArtifactTypes().maybeCreate(ArtifactTypeDefinition.ZIP_TYPE);
project.getDependencies().registerTransform(UnzipTransform.class, transformSpec -> {
transformSpec.getFrom()
.attribute(ArtifactTypeDefinition.ARTIFACT_TYPE_ATTRIBUTE, ArtifactTypeDefinition.ZIP_TYPE)
.attribute(BUNDLE_ATTRIBUTE, true);
transformSpec.getTo()
.attribute(ArtifactTypeDefinition.ARTIFACT_TYPE_ATTRIBUTE, ArtifactTypeDefinition.DIRECTORY_TYPE)
.attribute(BUNDLE_ATTRIBUTE, true);
transformSpec.getParameters().setAsFiletreeOutput(true);
});
}
private NamedDomainObjectContainer<ElasticsearchCluster> createTestClustersContainerExtension(
Project project,
Provider<TestClustersRegistry> testClustersRegistryProvider,
Provider<ReaperService> reaper,
Provider<JavaLauncher> fallbackJdk17Launcher
) {
// Create an extensions that allows describing clusters
NamedDomainObjectContainer<ElasticsearchCluster> container = project.container(
ElasticsearchCluster.class,
name -> new ElasticsearchCluster(
project.getPath(),
name,
project,
reaper,
testClustersRegistryProvider,
getFileSystemOperations(),
getArchiveOperations(),
getExecOperations(),
getFileOperations(),
new File(project.getBuildDir(), "testclusters"),
runtimeJavaProvider,
isReleasedVersion,
fallbackJdk17Launcher
)
);
project.getExtensions().add(EXTENSION_NAME, container);
container.configureEach(cluster -> cluster.systemProperty("ingest.geoip.downloader.enabled.default", "false"));
return container;
}
private void createListClustersTask(Project project, NamedDomainObjectContainer<ElasticsearchCluster> container) {
// Task is never up to date so we can pass an lambda for the task action
project.getTasks().register(LIST_TASK_NAME, task -> {
task.setGroup("ES cluster formation");
task.setDescription("Lists all ES clusters configured for this project");
task.doLast(
(Task t) -> container.forEach(cluster -> logger.lifecycle(" * {}: {}", cluster.getName(), cluster.getNumberOfNodes()))
);
});
}
static abstract | TestClustersPlugin |
java | micronaut-projects__micronaut-core | http-server/src/main/java/io/micronaut/http/server/body/AbstractFileBodyWriter.java | {
"start": 1501,
"end": 5545
} | class ____ permits InputStreamBodyWriter, StreamFileBodyWriter, SystemFileBodyWriter {
private static final Set<String> ENTITY_HEADERS = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
protected final HttpServerConfiguration.FileTypeHandlerConfiguration configuration;
static {
ENTITY_HEADERS.addAll(List.of(HttpHeaders.ALLOW, HttpHeaders.CONTENT_ENCODING, HttpHeaders.CONTENT_LANGUAGE, HttpHeaders.CONTENT_LENGTH, HttpHeaders.CONTENT_LOCATION, HttpHeaders.CONTENT_MD5, HttpHeaders.CONTENT_RANGE, HttpHeaders.CONTENT_TYPE, HttpHeaders.EXPIRES, HttpHeaders.LAST_MODIFIED));
}
AbstractFileBodyWriter(HttpServerConfiguration.FileTypeHandlerConfiguration configuration) {
this.configuration = configuration;
}
private static void copyNonEntityHeaders(MutableHttpResponse<?> from, MutableHttpResponse to) {
from.getHeaders().forEachValue((header, value) -> {
if (!ENTITY_HEADERS.contains(header)) {
to.getHeaders().add(header, value);
}
});
}
protected boolean handleIfModifiedAndHeaders(HttpRequest<?> request, MutableHttpResponse<?> response, FileCustomizableResponseType systemFile, MutableHttpResponse<?> nettyResponse) {
long lastModified = systemFile.getLastModified();
// Cache Validation
ZonedDateTime ifModifiedSince = request.getHeaders().getDate(HttpHeaders.IF_MODIFIED_SINCE);
if (ifModifiedSince != null) {
// Only compare up to the second because the datetime format we send to the client
// does not have milliseconds
long ifModifiedSinceDateSeconds = ifModifiedSince.toEpochSecond();
long fileLastModifiedSeconds = lastModified / 1000;
if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
return true;
}
}
response.getHeaders().contentTypeIfMissing(systemFile.getMediaType());
setDateAndCacheHeaders(response, lastModified);
systemFile.process(nettyResponse);
return false;
}
/**
* @param response The Http response
* @param lastModified The last modified
*/
protected void setDateAndCacheHeaders(MutableHttpResponse response, long lastModified) {
// Date header
MutableHttpHeaders headers = response.getHeaders();
LocalDateTime now = LocalDateTime.now();
if (!headers.contains(HttpHeaders.DATE)) {
headers.date(now);
}
// Add cache headers
LocalDateTime cacheSeconds = now.plus(configuration.getCacheSeconds(), ChronoUnit.SECONDS);
if (response.header(HttpHeaders.EXPIRES) == null) {
headers.expires(cacheSeconds);
}
if (response.header(HttpHeaders.CACHE_CONTROL) == null) {
HttpServerConfiguration.FileTypeHandlerConfiguration.CacheControlConfiguration cacheConfig = configuration.getCacheControl();
StringBuilder header = new StringBuilder(cacheConfig.getPublic() ? "public" : "private")
.append(", max-age=")
.append(configuration.getCacheSeconds());
response.header(HttpHeaders.CACHE_CONTROL, header.toString());
}
if (response.header(HttpHeaders.LAST_MODIFIED) == null) {
headers.lastModified(lastModified);
}
}
/**
* @param response The Http response
*/
protected void setDateHeader(MutableHttpResponse response) {
MutableHttpHeaders headers = response.getHeaders();
LocalDateTime now = LocalDateTime.now();
headers.date(now);
}
protected ByteBodyHttpResponse<?> notModified(ByteBodyFactory bodyFactory, MutableHttpResponse<?> originalResponse) {
MutableHttpResponse<Void> response = HttpResponse.notModified();
AbstractFileBodyWriter.copyNonEntityHeaders(originalResponse, response);
setDateHeader(response);
return ByteBodyHttpResponseWrapper.wrap(response, bodyFactory.createEmpty());
}
}
| AbstractFileBodyWriter |
java | elastic__elasticsearch | x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/ConnectorScheduling.java | {
"start": 1345,
"end": 5723
} | class ____ implements Writeable, ToXContentObject {
private static final String EVERYDAY_AT_MIDNIGHT = "0 0 0 * * ?";
private static final ParseField ACCESS_CONTROL_FIELD = new ParseField("access_control");
private static final ParseField FULL_FIELD = new ParseField("full");
private static final ParseField INCREMENTAL_FIELD = new ParseField("incremental");
private final ScheduleConfig accessControl;
private final ScheduleConfig full;
private final ScheduleConfig incremental;
/**
* @param accessControl connector access control sync schedule represented as {@link ScheduleConfig}
* @param full connector full sync schedule represented as {@link ScheduleConfig}
* @param incremental connector incremental sync schedule represented as {@link ScheduleConfig}
*/
private ConnectorScheduling(ScheduleConfig accessControl, ScheduleConfig full, ScheduleConfig incremental) {
this.accessControl = accessControl;
this.full = full;
this.incremental = incremental;
}
public ConnectorScheduling(StreamInput in) throws IOException {
this.accessControl = new ScheduleConfig(in);
this.full = new ScheduleConfig(in);
this.incremental = new ScheduleConfig(in);
}
public ScheduleConfig getAccessControl() {
return accessControl;
}
public ScheduleConfig getFull() {
return full;
}
public ScheduleConfig getIncremental() {
return incremental;
}
private static final ConstructingObjectParser<ConnectorScheduling, Void> PARSER = new ConstructingObjectParser<>(
"connector_scheduling",
true,
args -> new Builder().setAccessControl((ScheduleConfig) args[0])
.setFull((ScheduleConfig) args[1])
.setIncremental((ScheduleConfig) args[2])
.build()
);
static {
PARSER.declareField(
optionalConstructorArg(),
(p, c) -> ScheduleConfig.fromXContent(p),
ACCESS_CONTROL_FIELD,
ObjectParser.ValueType.OBJECT
);
PARSER.declareField(optionalConstructorArg(), (p, c) -> ScheduleConfig.fromXContent(p), FULL_FIELD, ObjectParser.ValueType.OBJECT);
PARSER.declareField(
optionalConstructorArg(),
(p, c) -> ScheduleConfig.fromXContent(p),
INCREMENTAL_FIELD,
ObjectParser.ValueType.OBJECT
);
}
public static ConnectorScheduling fromXContentBytes(BytesReference source, XContentType xContentType) {
try (XContentParser parser = XContentHelper.createParser(XContentParserConfiguration.EMPTY, source, xContentType)) {
return ConnectorScheduling.fromXContent(parser);
} catch (IOException e) {
throw new ElasticsearchParseException("Failed to parse: " + source.utf8ToString(), e);
}
}
public static ConnectorScheduling fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
{
if (accessControl != null) {
builder.field(ACCESS_CONTROL_FIELD.getPreferredName(), accessControl);
}
if (full != null) {
builder.field(FULL_FIELD.getPreferredName(), full);
}
if (incremental != null) {
builder.field(INCREMENTAL_FIELD.getPreferredName(), incremental);
}
}
builder.endObject();
return builder;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
accessControl.writeTo(out);
full.writeTo(out);
incremental.writeTo(out);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConnectorScheduling that = (ConnectorScheduling) o;
return Objects.equals(accessControl, that.accessControl)
&& Objects.equals(full, that.full)
&& Objects.equals(incremental, that.incremental);
}
@Override
public int hashCode() {
return Objects.hash(accessControl, full, incremental);
}
public static | ConnectorScheduling |
java | netty__netty | transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java | {
"start": 44886,
"end": 48640
} | class ____ extends AbstractChannelHandlerContext
implements ChannelOutboundHandler, ChannelInboundHandler {
private final Unsafe unsafe;
HeadContext(DefaultChannelPipeline pipeline) {
super(pipeline, null, HEAD_NAME, HeadContext.class);
unsafe = pipeline.channel().unsafe();
setAddComplete();
}
@Override
public ChannelHandler handler() {
return this;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
// NOOP
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
// NOOP
}
@Override
public void bind(
ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) {
unsafe.bind(localAddress, promise);
}
@Override
public void connect(
ChannelHandlerContext ctx,
SocketAddress remoteAddress, SocketAddress localAddress,
ChannelPromise promise) {
unsafe.connect(remoteAddress, localAddress, promise);
}
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) {
unsafe.disconnect(promise);
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) {
unsafe.close(promise);
}
@Override
public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) {
unsafe.deregister(promise);
}
@Override
public void read(ChannelHandlerContext ctx) {
unsafe.beginRead();
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
unsafe.write(msg, promise);
}
@Override
public void flush(ChannelHandlerContext ctx) {
unsafe.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.fireExceptionCaught(cause);
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
invokeHandlerAddedIfNeeded();
ctx.fireChannelRegistered();
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) {
ctx.fireChannelUnregistered();
// Remove all handlers sequentially if channel is closed and unregistered.
if (!channel.isOpen()) {
destroy();
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.fireChannelActive();
readIfIsAutoRead();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
ctx.fireChannelInactive();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.fireChannelRead(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.fireChannelReadComplete();
readIfIsAutoRead();
}
private void readIfIsAutoRead() {
if (channel.config().isAutoRead()) {
channel.read();
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
ctx.fireUserEventTriggered(evt);
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) {
ctx.fireChannelWritabilityChanged();
}
}
private abstract static | HeadContext |
java | quarkusio__quarkus | integration-tests/main/src/main/java/io/quarkus/it/context/ContextPropagationResource.java | {
"start": 704,
"end": 3613
} | class ____ {
@Inject
RequestBean doNotRemove;
@Inject
SmallRyeManagedExecutor smallRyeAllExec;
@Inject
SmallRyeManagedExecutor allExec;
@Inject
ThreadContext context;
@Inject
ThreadContext smallRyeContext;
@Inject
TransactionManager transactionManager;
@Path("managed-executor/created")
@Transactional
@GET
public CompletionStage<String> testManagedExecutorCreated(@Context UriInfo uriInfo) throws SystemException {
return testCompletionStage(allExec.completedFuture("OK"), uriInfo);
}
@Path("managed-executor/obtained")
@Transactional
@GET
public CompletionStage<String> testManagedExecutorObtained(@Context UriInfo uriInfo) throws SystemException {
// make sure we can also do that with CF we obtained from other sources, via ManagedExecutor
CompletableFuture<String> completedFuture = CompletableFuture.completedFuture("OK");
return testCompletionStage(allExec.copy(completedFuture), uriInfo);
}
@Path("thread-context")
@Transactional
@GET
public CompletionStage<String> testThreadContext(@Context UriInfo uriInfo) throws SystemException {
// make sure we can also do that with CF we obtained from other sources, via ThreadContext
CompletableFuture<String> completedFuture = CompletableFuture.completedFuture("OK");
return testCompletionStage(context.withContextCapture(completedFuture), uriInfo);
}
private CompletionStage<String> testCompletionStage(CompletionStage<String> stage, UriInfo uriInfo) throws SystemException {
// Transaction
Transaction t1 = transactionManager.getTransaction();
Assert.assertTrue(t1 != null);
Assert.assertTrue(t1.getStatus() == Status.STATUS_ACTIVE);
// ArC
Assert.assertTrue(Arc.container().instance(RequestBean.class).isAvailable());
RequestBean rb1 = Arc.container().instance(RequestBean.class).get();
Assert.assertTrue(rb1 != null);
String rbValue = rb1.callMe();
return stage.thenApplyAsync(text -> {
// RESTEasy
uriInfo.getAbsolutePath();
// ArC
RequestBean rb2 = Arc.container().instance(RequestBean.class).get();
Assert.assertTrue(rb2 != null);
Assert.assertTrue(rb2.callMe().contentEquals(rbValue));
// Transaction
Transaction t2;
try {
t2 = transactionManager.getTransaction();
} catch (SystemException e) {
throw new RuntimeException(e);
}
Assert.assertTrue(t1 == t2);
try {
Assert.assertTrue(t2.getStatus() == Status.STATUS_ACTIVE);
} catch (SystemException e) {
throw new RuntimeException(e);
}
return text;
});
}
}
| ContextPropagationResource |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/assertion/RecursiveAssertionDriver_PrimitiveFieldHandlingTest.java | {
"start": 3403,
"end": 3572
} | class ____ {
private int primitiveField = 0;
private Object objectField = new Object();
}
@SuppressWarnings("unused")
private | ClassWithPrimitiveAndObjectField |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CinderEndpointBuilderFactory.java | {
"start": 1571,
"end": 5871
} | interface ____
extends
EndpointProducerBuilder {
default AdvancedCinderEndpointBuilder advanced() {
return (AdvancedCinderEndpointBuilder) this;
}
/**
* OpenStack API version.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: V3
* Group: producer
*
* @param apiVersion the value to set
* @return the dsl builder
*/
default CinderEndpointBuilder apiVersion(String apiVersion) {
doSetProperty("apiVersion", apiVersion);
return this;
}
/**
* OpenStack configuration.
*
* The option is a: <code>org.openstack4j.core.transport.Config</code>
* type.
*
* Group: producer
*
* @param config the value to set
* @return the dsl builder
*/
default CinderEndpointBuilder config(org.openstack4j.core.transport.Config config) {
doSetProperty("config", config);
return this;
}
/**
* OpenStack configuration.
*
* The option will be converted to a
* <code>org.openstack4j.core.transport.Config</code> type.
*
* Group: producer
*
* @param config the value to set
* @return the dsl builder
*/
default CinderEndpointBuilder config(String config) {
doSetProperty("config", config);
return this;
}
/**
* Authentication domain.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: default
* Group: producer
*
* @param domain the value to set
* @return the dsl builder
*/
default CinderEndpointBuilder domain(String domain) {
doSetProperty("domain", domain);
return this;
}
/**
* The operation to do.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default CinderEndpointBuilder operation(String operation) {
doSetProperty("operation", operation);
return this;
}
/**
* OpenStack password.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: producer
*
* @param password the value to set
* @return the dsl builder
*/
default CinderEndpointBuilder password(String password) {
doSetProperty("password", password);
return this;
}
/**
* The project ID.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: producer
*
* @param project the value to set
* @return the dsl builder
*/
default CinderEndpointBuilder project(String project) {
doSetProperty("project", project);
return this;
}
/**
* OpenStack Cinder subsystem.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: producer
*
* @param subsystem the value to set
* @return the dsl builder
*/
default CinderEndpointBuilder subsystem(String subsystem) {
doSetProperty("subsystem", subsystem);
return this;
}
/**
* OpenStack username.
*
* The option is a: <code>java.lang.String</code> type.
*
* Required: true
* Group: producer
*
* @param username the value to set
* @return the dsl builder
*/
default CinderEndpointBuilder username(String username) {
doSetProperty("username", username);
return this;
}
}
/**
* Advanced builder for endpoint for the OpenStack Cinder component.
*/
public | CinderEndpointBuilder |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/MinIpAggregatorFunction.java | {
"start": 1044,
"end": 6522
} | class ____ implements AggregatorFunction {
private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of(
new IntermediateStateDesc("max", ElementType.BYTES_REF),
new IntermediateStateDesc("seen", ElementType.BOOLEAN) );
private final DriverContext driverContext;
private final MinIpAggregator.SingleState state;
private final List<Integer> channels;
public MinIpAggregatorFunction(DriverContext driverContext, List<Integer> channels,
MinIpAggregator.SingleState state) {
this.driverContext = driverContext;
this.channels = channels;
this.state = state;
}
public static MinIpAggregatorFunction create(DriverContext driverContext,
List<Integer> channels) {
return new MinIpAggregatorFunction(driverContext, channels, MinIpAggregator.initSingle());
}
public static List<IntermediateStateDesc> intermediateStateDesc() {
return INTERMEDIATE_STATE_DESC;
}
@Override
public int intermediateBlockCount() {
return INTERMEDIATE_STATE_DESC.size();
}
@Override
public void addRawInput(Page page, BooleanVector mask) {
if (mask.allFalse()) {
// Entire page masked away
} else if (mask.allTrue()) {
addRawInputNotMasked(page);
} else {
addRawInputMasked(page, mask);
}
}
private void addRawInputMasked(Page page, BooleanVector mask) {
BytesRefBlock valueBlock = page.getBlock(channels.get(0));
BytesRefVector valueVector = valueBlock.asVector();
if (valueVector == null) {
addRawBlock(valueBlock, mask);
return;
}
addRawVector(valueVector, mask);
}
private void addRawInputNotMasked(Page page) {
BytesRefBlock valueBlock = page.getBlock(channels.get(0));
BytesRefVector valueVector = valueBlock.asVector();
if (valueVector == null) {
addRawBlock(valueBlock);
return;
}
addRawVector(valueVector);
}
private void addRawVector(BytesRefVector valueVector) {
BytesRef valueScratch = new BytesRef();
for (int valuesPosition = 0; valuesPosition < valueVector.getPositionCount(); valuesPosition++) {
BytesRef valueValue = valueVector.getBytesRef(valuesPosition, valueScratch);
MinIpAggregator.combine(state, valueValue);
}
}
private void addRawVector(BytesRefVector valueVector, BooleanVector mask) {
BytesRef valueScratch = new BytesRef();
for (int valuesPosition = 0; valuesPosition < valueVector.getPositionCount(); valuesPosition++) {
if (mask.getBoolean(valuesPosition) == false) {
continue;
}
BytesRef valueValue = valueVector.getBytesRef(valuesPosition, valueScratch);
MinIpAggregator.combine(state, valueValue);
}
}
private void addRawBlock(BytesRefBlock valueBlock) {
BytesRef valueScratch = new BytesRef();
for (int p = 0; p < valueBlock.getPositionCount(); p++) {
int valueValueCount = valueBlock.getValueCount(p);
if (valueValueCount == 0) {
continue;
}
int valueStart = valueBlock.getFirstValueIndex(p);
int valueEnd = valueStart + valueValueCount;
for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) {
BytesRef valueValue = valueBlock.getBytesRef(valueOffset, valueScratch);
MinIpAggregator.combine(state, valueValue);
}
}
}
private void addRawBlock(BytesRefBlock valueBlock, BooleanVector mask) {
BytesRef valueScratch = new BytesRef();
for (int p = 0; p < valueBlock.getPositionCount(); p++) {
if (mask.getBoolean(p) == false) {
continue;
}
int valueValueCount = valueBlock.getValueCount(p);
if (valueValueCount == 0) {
continue;
}
int valueStart = valueBlock.getFirstValueIndex(p);
int valueEnd = valueStart + valueValueCount;
for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) {
BytesRef valueValue = valueBlock.getBytesRef(valueOffset, valueScratch);
MinIpAggregator.combine(state, valueValue);
}
}
}
@Override
public void addIntermediateInput(Page page) {
assert channels.size() == intermediateBlockCount();
assert page.getBlockCount() >= channels.get(0) + intermediateStateDesc().size();
Block maxUncast = page.getBlock(channels.get(0));
if (maxUncast.areAllValuesNull()) {
return;
}
BytesRefVector max = ((BytesRefBlock) maxUncast).asVector();
assert max.getPositionCount() == 1;
Block seenUncast = page.getBlock(channels.get(1));
if (seenUncast.areAllValuesNull()) {
return;
}
BooleanVector seen = ((BooleanBlock) seenUncast).asVector();
assert seen.getPositionCount() == 1;
BytesRef maxScratch = new BytesRef();
MinIpAggregator.combineIntermediate(state, max.getBytesRef(0, maxScratch), seen.getBoolean(0));
}
@Override
public void evaluateIntermediate(Block[] blocks, int offset, DriverContext driverContext) {
state.toIntermediate(blocks, offset, driverContext);
}
@Override
public void evaluateFinal(Block[] blocks, int offset, DriverContext driverContext) {
blocks[offset] = MinIpAggregator.evaluateFinal(state, driverContext);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append("[");
sb.append("channels=").append(channels);
sb.append("]");
return sb.toString();
}
@Override
public void close() {
state.close();
}
}
| MinIpAggregatorFunction |
java | apache__spark | common/unsafe/src/main/java/org/apache/spark/unsafe/memory/UnsafeMemoryAllocator.java | {
"start": 990,
"end": 2378
} | class ____ implements MemoryAllocator {
@Override
public MemoryBlock allocate(long size) throws OutOfMemoryError {
long address = Platform.allocateMemory(size);
MemoryBlock memory = new MemoryBlock(null, address, size);
if (MemoryAllocator.MEMORY_DEBUG_FILL_ENABLED) {
memory.fill(MemoryAllocator.MEMORY_DEBUG_FILL_CLEAN_VALUE);
}
return memory;
}
@Override
public void free(MemoryBlock memory) {
assert (memory.obj == null) :
"baseObject not null; are you trying to use the off-heap allocator to free on-heap memory?";
assert (memory.pageNumber != MemoryBlock.FREED_IN_ALLOCATOR_PAGE_NUMBER) :
"page has already been freed";
assert ((memory.pageNumber == MemoryBlock.NO_PAGE_NUMBER)
|| (memory.pageNumber == MemoryBlock.FREED_IN_TMM_PAGE_NUMBER)) :
"TMM-allocated pages must be freed via TMM.freePage(), not directly in allocator free()";
if (MemoryAllocator.MEMORY_DEBUG_FILL_ENABLED) {
memory.fill(MemoryAllocator.MEMORY_DEBUG_FILL_FREED_VALUE);
}
Platform.freeMemory(memory.offset);
// As an additional layer of defense against use-after-free bugs, we mutate the
// MemoryBlock to reset its pointer.
memory.offset = 0;
// Mark the page as freed (so we can detect double-frees).
memory.pageNumber = MemoryBlock.FREED_IN_ALLOCATOR_PAGE_NUMBER;
}
}
| UnsafeMemoryAllocator |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/aspectj/RuntimeTestWalker.java | {
"start": 1654,
"end": 2268
} | class ____ some AspectJ internal knowledge that should be
* pushed back into the AspectJ project in a future release.
*
* <p>It relies on implementation specific knowledge in AspectJ to break
* encapsulation and do something AspectJ was not designed to do: query
* the types of runtime tests that will be performed. The code here should
* migrate to {@code ShadowMatch.getVariablesInvolvedInRuntimeTest()}
* or some similar operation.
*
* <p>See <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=151593">Bug 151593</a>
*
* @author Adrian Colyer
* @author Ramnivas Laddad
* @since 2.0
*/
| encapsulates |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AS2EndpointBuilderFactory.java | {
"start": 73210,
"end": 75760
} | interface ____ extends EndpointProducerBuilder {
default AS2EndpointProducerBuilder basic() {
return (AS2EndpointProducerBuilder) this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedAS2EndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedAS2EndpointProducerBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
}
/**
* Builder for endpoint for the AS2 component.
*/
public | AdvancedAS2EndpointProducerBuilder |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/foreignkeys/disabled/InheritanceManyToManyForeignKeyTest.java | {
"start": 3372,
"end": 3481
} | class ____ extends AbstractEventsEntityModel {
@Id
@GeneratedValue
private Long id;
}
}
| ApplicationEvents |
java | hibernate__hibernate-orm | local-build-plugins/src/main/java/org/hibernate/orm/post/IndexManager.java | {
"start": 5796,
"end": 5988
} | class ____ - " + details.getFile()
.getAbsolutePath() );
}
}
catch (IllegalArgumentException e) {
throw new RuntimeException( "Problem indexing | file |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-documentstore/src/test/java/org/apache/hadoop/yarn/server/timelineservice/documentstore/TestDocumentStoreTimelineWriterImpl.java | {
"start": 2125,
"end": 4243
} | class ____ {
private final DocumentStoreWriter<TimelineDocument> documentStoreWriter = new
DummyDocumentStoreWriter<>();
private final Configuration conf = new Configuration();
private MockedStatic<DocumentStoreFactory> mockedFactory;
@BeforeEach
public void setUp() throws YarnException {
conf.set(DocumentStoreUtils.TIMELINE_SERVICE_DOCUMENTSTORE_DATABASE_NAME,
"TestDB");
conf.set(DocumentStoreUtils.TIMELINE_SERVICE_COSMOSDB_ENDPOINT,
"https://localhost:443");
conf.set(DocumentStoreUtils.TIMELINE_SERVICE_COSMOSDB_MASTER_KEY,
"1234567");
mockedFactory = Mockito.mockStatic(DocumentStoreFactory.class);
mockedFactory.when(() -> DocumentStoreFactory.createDocumentStoreWriter(
ArgumentMatchers.any(Configuration.class)))
.thenReturn(documentStoreWriter);
}
@AfterEach
public void tearDown() {
if (mockedFactory != null) {
mockedFactory.close();
}
}
@Test
public void testFailOnNoCosmosDBConfigs() throws Exception {
assertThrows(YarnException.class, ()->{
DocumentStoreUtils.validateCosmosDBConf(new Configuration());
});
}
@Test
public void testWritingToCosmosDB() throws Exception {
DocumentStoreTimelineWriterImpl timelineWriter = new
DocumentStoreTimelineWriterImpl();
timelineWriter.serviceInit(conf);
TimelineEntities entities = new TimelineEntities();
entities.addEntities(DocumentStoreTestUtils.bakeTimelineEntities());
entities.addEntity(DocumentStoreTestUtils.bakeTimelineEntityDoc()
.fetchTimelineEntity());
mockedFactory.verify(()->
DocumentStoreFactory.createDocumentStoreWriter(ArgumentMatchers.any(Configuration.class)),
times(4));
TimelineCollectorContext context = new TimelineCollectorContext();
context.setFlowName("TestFlow");
context.setAppId("DUMMY_APP_ID");
context.setClusterId("yarn_cluster");
context.setUserId("test_user");
timelineWriter.write(context, entities,
UserGroupInformation.createRemoteUser("test_user"));
}
} | TestDocumentStoreTimelineWriterImpl |
java | netty__netty | common/src/main/java/io/netty/util/concurrent/FastThreadLocalRunnable.java | {
"start": 706,
"end": 1254
} | class ____ implements Runnable {
private final Runnable runnable;
private FastThreadLocalRunnable(Runnable runnable) {
this.runnable = ObjectUtil.checkNotNull(runnable, "runnable");
}
@Override
public void run() {
try {
runnable.run();
} finally {
FastThreadLocal.removeAll();
}
}
static Runnable wrap(Runnable runnable) {
return runnable instanceof FastThreadLocalRunnable ? runnable : new FastThreadLocalRunnable(runnable);
}
}
| FastThreadLocalRunnable |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/BootLogging.java | {
"start": 7048,
"end": 10556
} | class ____ reflection %s")
void attemptingToDetermineComponentClassByReflection(String role);
@LogMessage(level = TRACE)
@Message(id = 160166, value = "Mapped collection: %s")
void mappedCollection(String role);
@LogMessage(level = TRACE)
@Message(id = 160167, value = "Mapping collection: %s -> %s")
void mappingCollectionToTable(String role, String tableName);
@LogMessage(level = TRACE)
@Message(id = 160168, value = "Binding natural id UniqueKey for entity: %s")
void bindingNaturalIdUniqueKey(String entityName);
@LogMessage(level = TRACE)
@Message(id = 160169, value = "Binding named query '%s' to [%s]")
void bindingNamedQuery(String queryName, String bindingTarget);
@LogMessage(level = TRACE)
@Message(id = 160170, value = "Binding named native query '%s' to [%s]")
void bindingNamedNativeQuery(String queryName, String bindingTarget);
@LogMessage(level = TRACE)
@Message(id = 160171, value = "Binding SQL result set mapping '%s' to [%s]")
void bindingSqlResultSetMapping(String name, String target);
@LogMessage(level = TRACE)
@Message(id = 160172, value = "Bound named stored procedure query: %s => %s")
void boundStoredProcedureQuery(String name, String procedure);
@LogMessage(level = TRACE)
@Message(id = 160173, value = "Adding global sequence generator with name: %s")
void addingGlobalSequenceGenerator(String name);
@LogMessage(level = TRACE)
@Message(id = 160174, value = "Adding global table generator with name: %s")
void addingGlobalTableGenerator(String name);
@LogMessage(level = TRACE)
@Message(id = 160175, value = "Binding entity with annotated class: %s")
void bindingEntityWithAnnotatedClass(String className);
@LogMessage(level = DEBUG)
@Message(id = 160176, value = "Import name [%s] overrode previous [{%s}]")
void importOverrodePrevious(String importName, String previous);
@LogMessage(level = TRACE)
@Message(id = 160177, value = "%s")
void mappedCollectionDetails(String details);
@LogMessage(level = TRACE)
@Message(id = 160178, value = "Mapping entity secondary table: %s -> %s")
void mappingEntitySecondaryTableToTable(String entityName, String tableName);
@LogMessage(level = DEBUG)
@Message(id = 160180, value = "Unexpected ServiceRegistry type [%s] encountered during building of MetadataSources; may cause problems later attempting to construct MetadataBuilder")
void unexpectedServiceRegistryType(String registryType);
@LogMessage(level = TRACE)
@Message(id = 160181, value = "Created database namespace [logicalName=%s, physicalName=%s]")
void createdDatabaseNamespace(Namespace.Name logicalName, Namespace.Name physicalName);
@LogMessage(level = DEBUG)
@Message(id = 160182, value = "Could load component class [%s]")
void couldLoadComponentClass(String className, @Cause Throwable ex);
@LogMessage(level = DEBUG)
@Message(id = 160183, value = "Unable to load explicit any-discriminator type name as Java Class - %s")
void unableToLoadExplicitAnyDiscriminatorType(String typeName);
@LogMessage(level = DEBUG)
@Message(id = 160184, value = "Ignoring exception thrown when trying to build IdentifierGenerator as part of Metadata building")
void ignoringExceptionBuildingIdentifierGenerator(@Cause Throwable ex);
@LogMessage(level = TRACE)
@Message(id = 160185, value = "Binding component [%s] to explicitly specified class [%s]")
void bindingComponentToExplicitClass(String role, String className);
@LogMessage(level = DEBUG)
@Message(id = 160186, value = "Unable to determine component | by |
java | apache__rocketmq | client/src/test/java/org/apache/rocketmq/client/trace/DefaultMQProducerWithOpenTracingTest.java | {
"start": 3070,
"end": 8126
} | class ____ {
@Spy
private MQClientInstance mQClientFactory = MQClientManager.getInstance().getOrCreateMQClientInstance(new ClientConfig());
@Mock
private MQClientAPIImpl mQClientAPIImpl;
private DefaultMQProducer producer;
private Message message;
private String topic = "FooBar";
private String producerGroupPrefix = "FooBar_PID";
private String producerGroupTemp = producerGroupPrefix + System.currentTimeMillis();
private String producerGroupTraceTemp = TopicValidator.RMQ_SYS_TRACE_TOPIC + System.currentTimeMillis();
private MockTracer tracer = new MockTracer();
@Before
public void init() throws Exception {
producer = new DefaultMQProducer(producerGroupTemp);
producer.getDefaultMQProducerImpl().registerSendMessageHook(
new SendMessageOpenTracingHookImpl(tracer));
producer.setNamesrvAddr("127.0.0.1:9876");
message = new Message(topic, new byte[] {'a', 'b', 'c'});
// disable trace to let mock trace work
producer.setEnableTrace(false);
producer.start();
Field field = DefaultMQProducerImpl.class.getDeclaredField("mQClientFactory");
field.setAccessible(true);
field.set(producer.getDefaultMQProducerImpl(), mQClientFactory);
field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
field.setAccessible(true);
field.set(mQClientFactory, mQClientAPIImpl);
producer.getDefaultMQProducerImpl().getMqClientFactory().registerProducer(producerGroupTemp, producer.getDefaultMQProducerImpl());
when(mQClientAPIImpl.sendMessage(anyString(), anyString(), any(Message.class), any(SendMessageRequestHeader.class), anyLong(), any(CommunicationMode.class),
nullable(SendMessageContext.class), any(DefaultMQProducerImpl.class))).thenCallRealMethod();
when(mQClientAPIImpl.sendMessage(anyString(), anyString(), any(Message.class), any(SendMessageRequestHeader.class), anyLong(), any(CommunicationMode.class),
nullable(SendCallback.class), nullable(TopicPublishInfo.class), nullable(MQClientInstance.class), anyInt(), nullable(SendMessageContext.class), any(DefaultMQProducerImpl.class)))
.thenReturn(createSendResult(SendStatus.SEND_OK));
}
@Test
public void testSendMessageSync_WithTrace_Success() throws RemotingException, InterruptedException, MQBrokerException, MQClientException {
producer.getDefaultMQProducerImpl().getMqClientFactory().registerProducer(producerGroupTraceTemp, producer.getDefaultMQProducerImpl());
when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createTopicRoute());
producer.send(message);
assertThat(tracer.finishedSpans().size()).isEqualTo(1);
MockSpan span = tracer.finishedSpans().get(0);
assertThat(span.tags().get(Tags.MESSAGE_BUS_DESTINATION.getKey())).isEqualTo(topic);
assertThat(span.tags().get(Tags.SPAN_KIND.getKey())).isEqualTo(Tags.SPAN_KIND_PRODUCER);
assertThat(span.tags().get(TraceConstants.ROCKETMQ_MSG_ID)).isEqualTo("123");
assertThat(span.tags().get(TraceConstants.ROCKETMQ_BODY_LENGTH)).isEqualTo(3);
assertThat(span.tags().get(TraceConstants.ROCKETMQ_REGION_ID)).isEqualTo("HZ");
assertThat(span.tags().get(TraceConstants.ROCKETMQ_MSG_TYPE)).isEqualTo(MessageType.Normal_Msg.name());
assertThat(span.tags().get(TraceConstants.ROCKETMQ_STORE_HOST)).isEqualTo("127.0.0.1:10911");
}
@After
public void terminate() {
producer.shutdown();
}
public static TopicRouteData createTopicRoute() {
TopicRouteData topicRouteData = new TopicRouteData();
topicRouteData.setFilterServerTable(new HashMap<>());
List<BrokerData> brokerDataList = new ArrayList<>();
BrokerData brokerData = new BrokerData();
brokerData.setBrokerName("BrokerA");
brokerData.setCluster("DefaultCluster");
HashMap<Long, String> brokerAddrs = new HashMap<>();
brokerAddrs.put(0L, "127.0.0.1:10911");
brokerData.setBrokerAddrs(brokerAddrs);
brokerDataList.add(brokerData);
topicRouteData.setBrokerDatas(brokerDataList);
List<QueueData> queueDataList = new ArrayList<>();
QueueData queueData = new QueueData();
queueData.setBrokerName("BrokerA");
queueData.setPerm(6);
queueData.setReadQueueNums(3);
queueData.setWriteQueueNums(4);
queueData.setTopicSysFlag(0);
queueDataList.add(queueData);
topicRouteData.setQueueDatas(queueDataList);
return topicRouteData;
}
private SendResult createSendResult(SendStatus sendStatus) {
SendResult sendResult = new SendResult();
sendResult.setMsgId("123");
sendResult.setOffsetMsgId("123");
sendResult.setQueueOffset(456);
sendResult.setSendStatus(sendStatus);
sendResult.setRegionId("HZ");
return sendResult;
}
}
| DefaultMQProducerWithOpenTracingTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/IdentifierNameTest.java | {
"start": 2578,
"end": 2923
} | class ____ {
private static int foo;
private static int fooBar;
private static int barFoo;
}
""")
.doTest();
}
@Test
public void nameWithUnderscores_mixedCasing() {
refactoringHelper
.addInputLines(
"Test.java",
"""
| Test |
java | apache__camel | components/camel-telemetry/src/test/java/org/apache/camel/telemetry/decorators/HttpMethods.java | {
"start": 858,
"end": 930
} | enum ____ {
DELETE,
GET,
PATCH,
POST,
PUT
}
| HttpMethods |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlDecoderTests.java | {
"start": 9423,
"end": 10020
} | class ____ extends Parent {
private String bar;
public Child() {
}
public Child(String foo, String bar) {
super(foo);
this.bar = bar;
}
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof Child other) {
return getBar().equals(other.getBar()) &&
getFoo().equals(other.getFoo());
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(getBar(), getFoo());
}
}
}
| Child |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/load/engine/executor/GlideExecutor.java | {
"start": 12981,
"end": 13622
} | class ____ implements ThreadFactory {
@Override
public Thread newThread(@NonNull Runnable runnable) {
return new Thread(runnable) {
@Override
public void run() {
// why PMD suppression is needed: https://github.com/pmd/pmd/issues/808
android.os.Process.setThreadPriority(DEFAULT_PRIORITY); // NOPMD AccessorMethodGeneration
super.run();
}
};
}
}
/**
* A {@link java.util.concurrent.ThreadFactory} that builds threads slightly above priority {@link
* android.os.Process#THREAD_PRIORITY_BACKGROUND}.
*/
private static final | DefaultPriorityThreadFactory |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/BareDotMetacharacterTest.java | {
"start": 1267,
"end": 1640
} | class ____ {
private static final String DOT = ".";
Object x = "foo.bar".split(".");
Object y = "foo.bonk".split(DOT);
Object z = Splitter.onPattern(".");
}
""")
.addOutputLines(
"Test.java",
"""
import com.google.common.base.Splitter;
| Test |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/fieldvisitor/StoredFieldLoaderTests.java | {
"start": 1356,
"end": 9756
} | class ____ extends ESTestCase {
private Document doc(String... values) {
assert values.length % 2 == 0;
Document doc = new Document();
for (int i = 0; i < values.length; i++) {
doc.add(new StoredField(values[i++], new BytesRef(values[i])));
}
return doc;
}
private StoredFieldsSpec fieldsSpec(
Set<String> storedFields,
Set<String> ignoredFields,
IgnoredSourceFieldMapper.IgnoredSourceFormat format
) {
return new StoredFieldsSpec(ignoredFields.isEmpty() == false, false, storedFields, format, ignoredFields);
}
public void testEmpty() throws IOException {
testStoredFieldLoader(
doc("foo", "lorem ipsum", "_ignored_source", "dolor sit amet"),
fieldsSpec(Set.of(), Set.of(), IgnoredSourceFieldMapper.IgnoredSourceFormat.COALESCED_SINGLE_IGNORED_SOURCE),
storedFields -> {
assertThat(storedFields, anEmptyMap());
}
);
}
public void testSingleIgnoredSourceNewFormat() throws IOException {
var fooValue = new IgnoredSourceFieldMapper.NameValue("foo", 0, new BytesRef("lorem ipsum"), null);
var doc = new Document();
doc.add(new StoredField("_ignored_source", IgnoredSourceFieldMapper.CoalescedIgnoredSourceEncoding.encode(List.of(fooValue))));
testIgnoredSourceLoader(
doc,
fieldsSpec(Set.of(), Set.of("foo"), IgnoredSourceFieldMapper.IgnoredSourceFormat.COALESCED_SINGLE_IGNORED_SOURCE),
ignoredFields -> {
assertThat(ignoredFields, containsInAnyOrder(containsInAnyOrder(fooValue)));
}
);
}
public void testSingleIgnoredSourceOldFormat() throws IOException {
testStoredFieldLoader(
doc("_ignored_source", "lorem ipsum"),
fieldsSpec(Set.of(), Set.of("foo"), IgnoredSourceFieldMapper.IgnoredSourceFormat.LEGACY_SINGLE_IGNORED_SOURCE),
storedFields -> {
assertThat(storedFields, hasEntry(equalTo("_ignored_source"), containsInAnyOrder(new BytesRef("lorem ipsum"))));
}
);
}
public void testMultiValueIgnoredSourceNewFormat() throws IOException {
var fooValue = new IgnoredSourceFieldMapper.NameValue("foo", 0, new BytesRef("lorem ipsum"), null);
var barValue = new IgnoredSourceFieldMapper.NameValue("bar", 0, new BytesRef("dolor sit amet"), null);
Document doc = new Document();
doc.add(new StoredField("_ignored_source", IgnoredSourceFieldMapper.CoalescedIgnoredSourceEncoding.encode(List.of(fooValue))));
doc.add(new StoredField("_ignored_source", IgnoredSourceFieldMapper.CoalescedIgnoredSourceEncoding.encode(List.of(barValue))));
testIgnoredSourceLoader(
doc,
fieldsSpec(Set.of(), Set.of("foo", "bar"), IgnoredSourceFieldMapper.IgnoredSourceFormat.COALESCED_SINGLE_IGNORED_SOURCE),
ignoredFields -> {
assertThat(ignoredFields, containsInAnyOrder(containsInAnyOrder(fooValue), containsInAnyOrder(barValue)));
}
);
}
public void testMultiValueIgnoredSourceOldFormat() throws IOException {
testStoredFieldLoader(
doc("_ignored_source", "lorem ipsum", "_ignored_source", "dolor sit amet"),
fieldsSpec(Set.of(), Set.of("foo", "bar"), IgnoredSourceFieldMapper.IgnoredSourceFormat.LEGACY_SINGLE_IGNORED_SOURCE),
storedFields -> {
assertThat(
storedFields,
hasEntry(equalTo("_ignored_source"), containsInAnyOrder(new BytesRef("lorem ipsum"), new BytesRef("dolor sit amet")))
);
}
);
}
public void testSingleStoredField() throws IOException {
testStoredFieldLoader(
doc("foo", "lorem ipsum"),
fieldsSpec(Set.of("foo"), Set.of(), IgnoredSourceFieldMapper.IgnoredSourceFormat.COALESCED_SINGLE_IGNORED_SOURCE),
storedFields -> {
assertThat(storedFields, hasEntry(equalTo("foo"), containsInAnyOrder(new BytesRef("lorem ipsum"))));
}
);
}
public void testMultiValueStoredField() throws IOException {
testStoredFieldLoader(
doc("foo", "lorem ipsum", "bar", "dolor sit amet"),
fieldsSpec(Set.of("foo", "bar"), Set.of(), IgnoredSourceFieldMapper.IgnoredSourceFormat.COALESCED_SINGLE_IGNORED_SOURCE),
storedFields -> {
assertThat(storedFields, hasEntry(equalTo("foo"), containsInAnyOrder(new BytesRef("lorem ipsum"))));
assertThat(storedFields, hasEntry(equalTo("bar"), containsInAnyOrder(new BytesRef("dolor sit amet"))));
}
);
}
public void testMixedStoredAndIgnoredFieldsNewFormat() throws IOException {
testStoredFieldLoader(
doc("foo", "lorem ipsum", "_ignored_source", "dolor sit amet"),
fieldsSpec(Set.of("foo"), Set.of("bar"), IgnoredSourceFieldMapper.IgnoredSourceFormat.COALESCED_SINGLE_IGNORED_SOURCE),
storedFields -> {
assertThat(storedFields, hasEntry(equalTo("foo"), containsInAnyOrder(new BytesRef("lorem ipsum"))));
assertThat(storedFields, hasEntry(equalTo("_ignored_source"), containsInAnyOrder(new BytesRef("dolor sit amet"))));
}
);
}
public void testMixedStoredAndIgnoredFieldsOldFormat() throws IOException {
testStoredFieldLoader(
doc("foo", "lorem ipsum", "_ignored_source", "dolor sit amet"),
fieldsSpec(Set.of("foo"), Set.of("bar"), IgnoredSourceFieldMapper.IgnoredSourceFormat.LEGACY_SINGLE_IGNORED_SOURCE),
storedFields -> {
assertThat(storedFields, hasEntry(equalTo("foo"), containsInAnyOrder(new BytesRef("lorem ipsum"))));
assertThat(storedFields, hasEntry(equalTo("_ignored_source"), containsInAnyOrder(new BytesRef("dolor sit amet"))));
}
);
}
public void testMixedStoredAndIgnoredFieldsLoadParent() throws IOException {
testStoredFieldLoader(
doc("foo", "lorem ipsum", "_ignored_source", "dolor sit amet"),
fieldsSpec(Set.of("foo"), Set.of("parent.bar"), IgnoredSourceFieldMapper.IgnoredSourceFormat.COALESCED_SINGLE_IGNORED_SOURCE),
storedFields -> {
assertThat(storedFields, hasEntry(equalTo("foo"), containsInAnyOrder(new BytesRef("lorem ipsum"))));
assertThat(storedFields, hasEntry(equalTo("_ignored_source"), containsInAnyOrder(new BytesRef("dolor sit amet"))));
}
);
}
private void testStoredFieldLoader(Document doc, StoredFieldsSpec spec, Consumer<Map<String, List<Object>>> storedFieldsTest)
throws IOException {
testLoader(doc, spec, StoredFieldLoader.class, storedFieldsTest);
}
private void testIgnoredSourceLoader(
Document doc,
StoredFieldsSpec spec,
Consumer<List<List<IgnoredSourceFieldMapper.NameValue>>> ignoredFieldEntriesTest
) throws IOException {
testLoader(doc, spec, IgnoredSourceFieldLoader.class, storedFields -> {
@SuppressWarnings("unchecked")
List<List<IgnoredSourceFieldMapper.NameValue>> ignoredFieldEntries = (List<
List<IgnoredSourceFieldMapper.NameValue>>) (Object) storedFields.get("_ignored_source");
ignoredFieldEntriesTest.accept(ignoredFieldEntries);
});
}
private void testLoader(
Document doc,
StoredFieldsSpec spec,
Class<? extends StoredFieldLoader> expectedLoaderClass,
Consumer<Map<String, List<Object>>> storedFieldsTest
) throws IOException {
try (Directory dir = newDirectory(); IndexWriter iw = new IndexWriter(dir, newIndexWriterConfig(Lucene.STANDARD_ANALYZER))) {
iw.addDocument(doc);
try (DirectoryReader reader = DirectoryReader.open(iw)) {
StoredFieldLoader loader = StoredFieldLoader.fromSpec(spec);
assertThat(loader, Matchers.isA(expectedLoaderClass));
var leafLoader = loader.getLoader(reader.leaves().getFirst(), new int[] { 0 });
leafLoader.advanceTo(0);
storedFieldsTest.accept(leafLoader.storedFields());
}
}
}
}
| StoredFieldLoaderTests |
java | apache__dubbo | dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Quit.java | {
"start": 1185,
"end": 1352
} | class ____ implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
return QosConstants.CLOSE;
}
}
| Quit |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-csi/src/main/java/org/apache/hadoop/yarn/csi/translator/NodePublishVolumeRequestProtoTranslator.java | {
"start": 1104,
"end": 1306
} | class ____ to transform a YARN side NodePublishVolumeRequest
* to corresponding CSI protocol message.
* @param <A> YARN NodePublishVolumeRequest
* @param <B> CSI NodePublishVolumeRequest
*/
public | helps |
java | elastic__elasticsearch | x-pack/plugin/analytics/src/main/java/org/elasticsearch/xpack/analytics/action/AnalyticsInfoTransportAction.java | {
"start": 660,
"end": 1187
} | class ____ extends XPackInfoFeatureTransportAction {
@Inject
public AnalyticsInfoTransportAction(TransportService transportService, ActionFilters actionFilters) {
super(XPackInfoFeatureAction.ANALYTICS.name(), transportService, actionFilters);
}
@Override
public String name() {
return XPackField.ANALYTICS;
}
@Override
public boolean available() {
return true;
}
@Override
public boolean enabled() {
return true;
}
}
| AnalyticsInfoTransportAction |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/java/typeutils/PojoTypeExtractionTest.java | {
"start": 34304,
"end": 34409
} | class ____ {
public int foo, bar;
public FooBarPojo() {}
}
public static | FooBarPojo |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java | {
"start": 86612,
"end": 86828
} | class ____ extends PropertyEditorSupport {
@Override
public void setAsText(String text) {
String[] content = text.split(",");
setValue(new Person(content[1], content[0]));
}
}
static | PersonPropertyEditor |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/AbstractStringLayoutTest.java | {
"start": 1639,
"end": 4433
} | class ____ extends AbstractStringLayout {
public static int DEFAULT_STRING_BUILDER_SIZE = AbstractStringLayout.DEFAULT_STRING_BUILDER_SIZE;
public static int MAX_STRING_BUILDER_SIZE = AbstractStringLayout.MAX_STRING_BUILDER_SIZE;
public ConcreteStringLayout() {
// Configuration explicitly null
super(null, Charset.defaultCharset(), serializer, serializer);
}
public static StringBuilder getStringBuilder() {
return AbstractStringLayout.getStringBuilder();
}
@Override
public String toSerializable(final LogEvent event) {
return null;
}
}
@Test
void testGetStringBuilderCapacityRestrictedToMax() {
final StringBuilder sb = ConcreteStringLayout.getStringBuilder();
final int initialCapacity = sb.capacity();
assertEquals(ConcreteStringLayout.DEFAULT_STRING_BUILDER_SIZE, sb.capacity(), "initial capacity");
final int SMALL = 100;
final String smallMessage = new String(new char[SMALL]);
sb.append(smallMessage);
assertEquals(initialCapacity, sb.capacity(), "capacity not grown");
assertEquals(SMALL, sb.length(), "length=msg length");
final StringBuilder sb2 = ConcreteStringLayout.getStringBuilder();
assertEquals(sb2.capacity(), initialCapacity, "capacity unchanged");
assertEquals(0, sb2.length(), "empty, ready for use");
final int LARGE = ConcreteStringLayout.MAX_STRING_BUILDER_SIZE * 2;
final String largeMessage = new String(new char[LARGE]);
sb2.append(largeMessage);
assertTrue(sb2.capacity() >= LARGE, "capacity grown to fit msg length");
assertTrue(
sb2.capacity() >= ConcreteStringLayout.MAX_STRING_BUILDER_SIZE,
"capacity is now greater than max length");
assertEquals(LARGE, sb2.length(), "length=msg length");
sb2.setLength(0); // set 0 before next getStringBuilder() call
assertEquals(0, sb2.length(), "empty, cleared");
assertTrue(sb2.capacity() >= ConcreteStringLayout.MAX_STRING_BUILDER_SIZE, "capacity remains very large");
final StringBuilder sb3 = ConcreteStringLayout.getStringBuilder();
assertEquals(
ConcreteStringLayout.MAX_STRING_BUILDER_SIZE,
sb3.capacity(),
"capacity, trimmed to MAX_STRING_BUILDER_SIZE");
assertEquals(0, sb3.length(), "empty, ready for use");
}
@Test
void testNullConfigurationIsAllowed() {
try {
final ConcreteStringLayout layout = new ConcreteStringLayout();
layout.serializeToString(serializer);
} catch (NullPointerException e) {
fail(e);
}
}
}
| ConcreteStringLayout |
java | apache__camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpProducerFileWithPathIT.java | {
"start": 1323,
"end": 3903
} | class ____ extends SftpServerTestSupport {
private String getFtpUrl() {
return "sftp://admin@localhost:{{ftp.server.port}}/{{ftp.root.dir}}?password=admin&knownHostsFile="
+ service.getKnownHostsFile();
}
@Test
public void testProducerFileWithPath() throws Exception {
template.sendBodyAndHeader(getFtpUrl(), "Hello World", Exchange.FILE_NAME, "hello/claus.txt");
File file = ftpFile("hello/claus.txt").toFile();
assertTrue(file.exists(), "The uploaded file should exists");
assertEquals("Hello World", IOConverter.toString(file, null));
}
@Test
public void testProducerFileWithPathTwice() throws Exception {
template.sendBodyAndHeader(getFtpUrl(), "Hello World", Exchange.FILE_NAME, "hello/claus.txt");
template.sendBodyAndHeader(getFtpUrl(), "Hello Again World", Exchange.FILE_NAME, "hello/andrea.txt");
File file = ftpFile("hello/claus.txt").toFile();
assertTrue(file.exists(), "The uploaded file should exists");
assertEquals("Hello World", IOConverter.toString(file, null));
file = ftpFile("hello/andrea.txt").toFile();
assertTrue(file.exists(), "The uploaded file should exists");
assertEquals("Hello Again World", IOConverter.toString(file, null));
}
@Test
public void testProducerFileWithPathExistDirCheckUsingLs() throws Exception {
template.sendBodyAndHeader(getFtpUrl() + "&existDirCheckUsingLs=false", "Bye World", Exchange.FILE_NAME,
"bye/andrea.txt");
File file = ftpFile("bye/andrea.txt").toFile();
assertTrue(file.exists(), "The uploaded file should exists");
assertEquals("Bye World", IOConverter.toString(file, null));
}
@Test
public void testProducerFileWithPathExistDirCheckUsingLsTwice() throws Exception {
template.sendBodyAndHeader(getFtpUrl() + "&existDirCheckUsingLs=false", "Bye World", Exchange.FILE_NAME,
"bye/andrea.txt");
template.sendBodyAndHeader(getFtpUrl() + "&existDirCheckUsingLs=false", "Bye Again World", Exchange.FILE_NAME,
"bye/claus.txt");
File file = ftpFile("bye/andrea.txt").toFile();
assertTrue(file.exists(), "The uploaded file should exists");
assertEquals("Bye World", IOConverter.toString(file, null));
file = ftpFile("bye/claus.txt").toFile();
assertTrue(file.exists(), "The uploaded file should exists");
assertEquals("Bye Again World", IOConverter.toString(file, null));
}
}
| SftpProducerFileWithPathIT |
java | apache__camel | components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorConsumerSuspendResumeTest.java | {
"start": 1208,
"end": 3297
} | class ____ extends CamelTestSupport {
@Test
void testSuspendResume() throws Exception {
final MockEndpoint mock = getMockEndpoint("mock:bar");
mock.expectedMessageCount(1);
template.sendBody("disruptor:foo", "A");
mock.assertIsSatisfied();
assertEquals("Started", context.getRouteController().getRouteStatus("foo").name());
assertEquals("Started", context.getRouteController().getRouteStatus("bar").name());
// suspend bar consumer (not the route)
final DisruptorConsumer consumer = (DisruptorConsumer) context.getRoute("bar").getConsumer();
ServiceHelper.suspendService(consumer);
assertEquals("Suspended", consumer.getStatus().name());
// send a message to the route but the consumer is suspended
// so it should not route it
MockEndpoint.resetMocks(context);
mock.expectedMessageCount(0);
// wait a bit to ensure consumer is suspended, as it could be in a poll mode where
// it would poll and route (there is a little slack (up till 1 sec) before suspension is empowered)
Awaitility.await().untilAsserted(() -> {
template.sendBody("disruptor:foo", "B");
// wait 2 sec to ensure disruptor consumer thread would have tried to poll otherwise
mock.assertIsSatisfied(2000);
});
// resume consumer
MockEndpoint.resetMocks(context);
mock.expectedMessageCount(1);
// resume bar consumer (not the route)
ServiceHelper.resumeService(consumer);
assertEquals("Started", consumer.getStatus().name());
// the message should be routed now
mock.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("disruptor:foo").routeId("foo").to("disruptor:bar");
from("disruptor:bar").routeId("bar").to("mock:bar");
}
};
}
}
| DisruptorConsumerSuspendResumeTest |
java | apache__kafka | server-common/src/main/java/org/apache/kafka/server/metrics/KafkaMetricsGroup.java | {
"start": 1597,
"end": 6886
} | class ____ will impact the mbean name and
* that will break the backward compatibility.
*/
public KafkaMetricsGroup(String packageName, String simpleName) {
this.pkg = packageName;
this.simpleName = simpleName;
}
/**
* Creates a new MetricName object for gauges, meters, etc. created for this
* metrics group.
* @param name Descriptive name of the metric.
* @param tags Additional attributes which mBean will have.
* @return Sanitized metric name object.
*/
public MetricName metricName(String name, Map<String, String> tags) {
return explicitMetricName(this.pkg, this.simpleName, name, tags);
}
private static MetricName explicitMetricName(String group, String typeName,
String name, Map<String, String> tags) {
StringBuilder nameBuilder = new StringBuilder(100);
nameBuilder.append(group);
nameBuilder.append(":type=");
nameBuilder.append(typeName);
if (!name.isEmpty()) {
nameBuilder.append(",name=");
nameBuilder.append(name);
}
String scope = toScope(tags).orElse(null);
Optional<String> tagsName = toMBeanName(tags);
tagsName.ifPresent(s -> nameBuilder.append(",").append(s));
return new MetricName(group, typeName, name, scope, nameBuilder.toString());
}
public <T> Gauge<T> newGauge(String name, Supplier<T> metric, Map<String, String> tags) {
return newGauge(metricName(name, tags), metric);
}
public <T> Gauge<T> newGauge(String name, Supplier<T> metric) {
return newGauge(name, metric, Map.of());
}
public <T> Gauge<T> newGauge(MetricName name, Supplier<T> metric) {
return KafkaYammerMetrics.defaultRegistry().newGauge(name, new Gauge<T>() {
@Override
public T value() {
return metric.get();
}
});
}
public final Meter newMeter(String name, String eventType,
TimeUnit timeUnit, Map<String, String> tags) {
return KafkaYammerMetrics.defaultRegistry().newMeter(metricName(name, tags), eventType, timeUnit);
}
public final Meter newMeter(String name, String eventType,
TimeUnit timeUnit) {
return newMeter(name, eventType, timeUnit, Map.of());
}
public final Meter newMeter(MetricName metricName, String eventType, TimeUnit timeUnit) {
return KafkaYammerMetrics.defaultRegistry().newMeter(metricName, eventType, timeUnit);
}
public final Histogram newHistogram(String name, boolean biased, Map<String, String> tags) {
return KafkaYammerMetrics.defaultRegistry().newHistogram(metricName(name, tags), biased);
}
public final Histogram newHistogram(String name) {
return newHistogram(name, true, Map.of());
}
public final Timer newTimer(String name, TimeUnit durationUnit, TimeUnit rateUnit, Map<String, String> tags) {
return KafkaYammerMetrics.defaultRegistry().newTimer(metricName(name, tags), durationUnit, rateUnit);
}
public final Timer newTimer(String name, TimeUnit durationUnit, TimeUnit rateUnit) {
return newTimer(name, durationUnit, rateUnit, Map.of());
}
public final Timer newTimer(MetricName metricName, TimeUnit durationUnit, TimeUnit rateUnit) {
return KafkaYammerMetrics.defaultRegistry().newTimer(metricName, durationUnit, rateUnit);
}
public final void removeMetric(String name, Map<String, String> tags) {
KafkaYammerMetrics.defaultRegistry().removeMetric(metricName(name, tags));
}
public final void removeMetric(String name) {
removeMetric(name, Map.of());
}
public final void removeMetric(MetricName metricName) {
KafkaYammerMetrics.defaultRegistry().removeMetric(metricName);
}
private static Optional<String> toMBeanName(Map<String, String> tags) {
List<Map.Entry<String, String>> filteredTags = tags.entrySet().stream()
.filter(entry -> !entry.getValue().isEmpty())
.toList();
if (!filteredTags.isEmpty()) {
String tagsString = filteredTags.stream()
.map(entry -> entry.getKey() + "=" + Sanitizer.jmxSanitize(entry.getValue()))
.collect(Collectors.joining(","));
return Optional.of(tagsString);
} else {
return Optional.empty();
}
}
private static Optional<String> toScope(Map<String, String> tags) {
List<Map.Entry<String, String>> filteredTags = tags.entrySet().stream()
.filter(entry -> !entry.getValue().isEmpty())
.toList();
if (!filteredTags.isEmpty()) {
// convert dot to _ since reporters like Graphite typically use dot to represent hierarchy
String tagsString = filteredTags.stream()
.sorted(Map.Entry.comparingByKey())
.map(entry -> entry.getKey() + "." + entry.getValue().replaceAll("\\.", "_"))
.collect(Collectors.joining("."));
return Optional.of(tagsString);
} else {
return Optional.empty();
}
}
}
| name |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/genericsinheritance/ParentHierarchy22.java | {
"start": 209,
"end": 281
} | class ____ extends ParentHierarchy2<ChildHierarchy22> {
}
| ParentHierarchy22 |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java | {
"start": 2036,
"end": 2727
} | class ____ resolving method arguments from a named value.
* Request parameters, request headers, and path variables are examples of named
* values. Each may have a name, a required flag, and a default value.
*
* <p>Subclasses define how to do the following:
* <ul>
* <li>Obtain named value information for a method parameter
* <li>Resolve names into argument values
* <li>Handle missing argument values when argument values are required
* <li>Optionally handle a resolved value
* </ul>
*
* <p>A default value string can contain ${...} placeholders and Spring Expression
* Language #{...} expressions. For this to work a
* {@link ConfigurableBeanFactory} must be supplied to the | for |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/authentication/ProviderManager.java | {
"start": 12854,
"end": 13438
} | interface ____ have its
* {@link CredentialsContainer#eraseCredentials() eraseCredentials} method called
* before it is returned from the {@code authenticate()} method.
* @param eraseSecretData set to {@literal false} to retain the credentials data in
* memory. Defaults to {@literal true}.
*/
public void setEraseCredentialsAfterAuthentication(boolean eraseSecretData) {
this.eraseCredentialsAfterAuthentication = eraseSecretData;
}
public boolean isEraseCredentialsAfterAuthentication() {
return this.eraseCredentialsAfterAuthentication;
}
private static final | will |
java | google__dagger | javatests/dagger/hilt/android/testing/testinstallin/TestInstallInModules.java | {
"start": 1432,
"end": 1603
} | class ____ {
Class<?> moduleClass;
Bar(Class<?> moduleClass) {
this.moduleClass = moduleClass;
}
}
@Module
@InstallIn(SingletonComponent.class)
| Bar |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/aot/TestContextAotGenerator.java | {
"start": 3352,
"end": 9373
} | class ____ {
/**
* JVM system property used to set the {@code failOnError} flag: {@value}.
* <p>The {@code failOnError} flag controls whether errors encountered during
* AOT processing in the <em>Spring TestContext Framework</em> should result
* in an exception that fails the overall process.
* <p>Defaults to {@code true}.
* <p>Supported values include {@code true} or {@code false}, ignoring case.
* For example, the default may be changed to {@code false} by supplying
* the following JVM system property via the command line.
* <pre style="code">-Dspring.test.aot.processing.failOnError=false</pre>
* <p>May alternatively be configured via the
* {@link org.springframework.core.SpringProperties SpringProperties}
* mechanism.
* @since 6.1
*/
public static final String FAIL_ON_ERROR_PROPERTY_NAME = "spring.test.aot.processing.failOnError";
private static final Log logger = LogFactory.getLog(TestContextAotGenerator.class);
private static final Predicate<? super Class<?>> isDisabledInAotMode =
testClass -> TestContextAnnotationUtils.hasAnnotation(testClass, DisabledInAotMode.class);
private final ApplicationContextAotGenerator aotGenerator = new ApplicationContextAotGenerator();
private final AotServices<TestRuntimeHintsRegistrar> testRuntimeHintsRegistrars;
private final MergedContextConfigurationRuntimeHints mergedConfigRuntimeHints =
new MergedContextConfigurationRuntimeHints();
private final AtomicInteger sequence = new AtomicInteger();
private final GeneratedFiles generatedFiles;
private final RuntimeHints runtimeHints;
final boolean failOnError;
/**
* Create a new {@link TestContextAotGenerator} that uses the supplied
* {@link GeneratedFiles}.
* @param generatedFiles the {@code GeneratedFiles} to use
* @see #TestContextAotGenerator(GeneratedFiles, RuntimeHints)
*/
public TestContextAotGenerator(GeneratedFiles generatedFiles) {
this(generatedFiles, new RuntimeHints());
}
/**
* Create a new {@link TestContextAotGenerator} that uses the supplied
* {@link GeneratedFiles} and {@link RuntimeHints}.
* <p>This constructor looks up the value of the {@code failOnError} flag via
* the {@value #FAIL_ON_ERROR_PROPERTY_NAME} property, defaulting to
* {@code true} if the property is not set.
* @param generatedFiles the {@code GeneratedFiles} to use
* @param runtimeHints the {@code RuntimeHints} to use
* @see #TestContextAotGenerator(GeneratedFiles, RuntimeHints, boolean)
*/
public TestContextAotGenerator(GeneratedFiles generatedFiles, RuntimeHints runtimeHints) {
this(generatedFiles, runtimeHints, getFailOnErrorFlag());
}
/**
* Create a new {@link TestContextAotGenerator} that uses the supplied
* {@link GeneratedFiles}, {@link RuntimeHints}, and {@code failOnError} flag.
* @param generatedFiles the {@code GeneratedFiles} to use
* @param runtimeHints the {@code RuntimeHints} to use
* @param failOnError {@code true} if errors encountered during AOT processing
* should result in an exception that fails the overall process
* @since 6.1
*/
public TestContextAotGenerator(GeneratedFiles generatedFiles, RuntimeHints runtimeHints, boolean failOnError) {
this.testRuntimeHintsRegistrars = AotServices.factories().load(TestRuntimeHintsRegistrar.class);
this.generatedFiles = generatedFiles;
this.runtimeHints = runtimeHints;
this.failOnError = failOnError;
}
/**
* Get the {@link RuntimeHints} gathered during {@linkplain #processAheadOfTime(Stream)
* AOT processing}.
*/
public final RuntimeHints getRuntimeHints() {
return this.runtimeHints;
}
/**
* Process each of the supplied Spring integration test classes and generate
* AOT artifacts.
* @throws TestContextAotException if an error occurs during AOT processing
*/
public void processAheadOfTime(Stream<Class<?>> testClasses) throws TestContextAotException {
Assert.state(!AotDetector.useGeneratedArtifacts(), "Cannot perform AOT processing during AOT run-time execution");
try {
resetAotFactories();
Set<Class<? extends RuntimeHintsRegistrar>> coreRuntimeHintsRegistrarClasses = new LinkedHashSet<>();
ReflectiveRuntimeHintsRegistrar reflectiveRuntimeHintsRegistrar = new ReflectiveRuntimeHintsRegistrar();
MultiValueMap<MergedContextConfiguration, Class<?>> mergedConfigMappings = new LinkedMultiValueMap<>();
ClassLoader classLoader = getClass().getClassLoader();
testClasses.forEach(testClass -> {
MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass);
mergedConfigMappings.add(mergedConfig, testClass);
collectRuntimeHintsRegistrarClasses(testClass, coreRuntimeHintsRegistrarClasses);
reflectiveRuntimeHintsRegistrar.registerRuntimeHints(this.runtimeHints, testClass);
this.testRuntimeHintsRegistrars.forEach(registrar -> {
if (logger.isTraceEnabled()) {
logger.trace("Processing RuntimeHints contribution from class [%s]"
.formatted(registrar.getClass().getCanonicalName()));
}
registrar.registerHints(this.runtimeHints, testClass, classLoader);
});
});
coreRuntimeHintsRegistrarClasses.stream()
.map(BeanUtils::instantiateClass)
.forEach(registrar -> {
if (logger.isTraceEnabled()) {
logger.trace("Processing RuntimeHints contribution from class [%s]"
.formatted(registrar.getClass().getCanonicalName()));
}
registrar.registerHints(this.runtimeHints, classLoader);
});
MultiValueMap<ClassName, Class<?>> initializerClassMappings = processAheadOfTime(mergedConfigMappings);
generateAotTestContextInitializerMappings(initializerClassMappings);
generateAotTestAttributeMappings();
registerSkippedExceptionTypes();
}
finally {
resetAotFactories();
}
}
/**
* Collect all {@link RuntimeHintsRegistrar} classes declared via
* {@link ImportRuntimeHints @ImportRuntimeHints} on the supplied test class
* and add them to the supplied {@link Set}.
* @param testClass the test | TestContextAotGenerator |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecPythonOverAggregate.java | {
"start": 4182,
"end": 18819
} | class ____ extends ExecNodeBase<RowData>
implements StreamExecNode<RowData>, SingleTransformationTranslator<RowData> {
private static final Logger LOG = LoggerFactory.getLogger(StreamExecPythonOverAggregate.class);
public static final String PYTHON_OVER_AGGREGATE_TRANSFORMATION = "python-over-aggregate";
public static final String FIELD_NAME_OVER_SPEC = "overSpec";
private static final String
ARROW_PYTHON_OVER_WINDOW_RANGE_ROW_TIME_AGGREGATE_FUNCTION_OPERATOR_NAME =
"org.apache.flink.table.runtime.operators.python.aggregate.arrow.stream."
+ "StreamArrowPythonRowTimeBoundedRangeOperator";
private static final String
ARROW_PYTHON_OVER_WINDOW_RANGE_PROC_TIME_AGGREGATE_FUNCTION_OPERATOR_NAME =
"org.apache.flink.table.runtime.operators.python.aggregate.arrow.stream."
+ "StreamArrowPythonProcTimeBoundedRangeOperator";
private static final String
ARROW_PYTHON_OVER_WINDOW_ROWS_ROW_TIME_AGGREGATE_FUNCTION_OPERATOR_NAME =
"org.apache.flink.table.runtime.operators.python.aggregate.arrow.stream."
+ "StreamArrowPythonRowTimeBoundedRowsOperator";
private static final String
ARROW_PYTHON_OVER_WINDOW_ROWS_PROC_TIME_AGGREGATE_FUNCTION_OPERATOR_NAME =
"org.apache.flink.table.runtime.operators.python.aggregate.arrow.stream."
+ "StreamArrowPythonProcTimeBoundedRowsOperator";
@JsonProperty(FIELD_NAME_OVER_SPEC)
private final OverSpec overSpec;
public StreamExecPythonOverAggregate(
ReadableConfig tableConfig,
OverSpec overSpec,
InputProperty inputProperty,
RowType outputType,
String description) {
this(
ExecNodeContext.newNodeId(),
ExecNodeContext.newContext(StreamExecPythonOverAggregate.class),
ExecNodeContext.newPersistedConfig(
StreamExecPythonOverAggregate.class, tableConfig),
overSpec,
Collections.singletonList(inputProperty),
outputType,
description);
}
@JsonCreator
public StreamExecPythonOverAggregate(
@JsonProperty(FIELD_NAME_ID) int id,
@JsonProperty(FIELD_NAME_TYPE) ExecNodeContext context,
@JsonProperty(FIELD_NAME_CONFIGURATION) ReadableConfig persistedConfig,
@JsonProperty(FIELD_NAME_OVER_SPEC) OverSpec overSpec,
@JsonProperty(FIELD_NAME_INPUT_PROPERTIES) List<InputProperty> inputProperties,
@JsonProperty(FIELD_NAME_OUTPUT_TYPE) RowType outputType,
@JsonProperty(FIELD_NAME_DESCRIPTION) String description) {
super(id, context, persistedConfig, inputProperties, outputType, description);
checkArgument(inputProperties.size() == 1);
this.overSpec = checkNotNull(overSpec);
}
@SuppressWarnings("unchecked")
@Override
protected Transformation<RowData> translateToPlanInternal(
PlannerBase planner, ExecNodeConfig config) {
if (overSpec.getGroups().size() > 1) {
throw new TableException("All aggregates must be computed on the same window.");
}
final OverSpec.GroupSpec group = overSpec.getGroups().get(0);
final int[] orderKeys = group.getSort().getFieldIndices();
final boolean[] isAscendingOrders = group.getSort().getAscendingOrders();
if (orderKeys.length != 1 || isAscendingOrders.length != 1) {
throw new TableException("The window can only be ordered by a single time column.");
}
if (!isAscendingOrders[0]) {
throw new TableException("The window can only be ordered in ASCENDING mode.");
}
final int[] partitionKeys = overSpec.getPartition().getFieldIndices();
if (partitionKeys.length > 0 && config.getStateRetentionTime() < 0) {
LOG.warn(
"No state retention interval configured for a query which accumulates state. "
+ "Please provide a query configuration with valid retention interval to prevent "
+ "excessive state size. You may specify a retention time of 0 to not clean up the state.");
}
final ExecEdge inputEdge = getInputEdges().get(0);
final Transformation<RowData> inputTransform =
(Transformation<RowData>) inputEdge.translateToPlan(planner);
final RowType inputRowType = (RowType) inputEdge.getOutputType();
final int orderKey = orderKeys[0];
final LogicalType orderKeyType = inputRowType.getFields().get(orderKey).getType();
// check time field && identify window rowtime attribute
final int rowTimeIdx;
if (isRowtimeAttribute(orderKeyType)) {
rowTimeIdx = orderKey;
} else if (isProctimeAttribute(orderKeyType)) {
rowTimeIdx = -1;
} else {
throw new TableException(
"OVER windows' ordering in stream mode must be defined on a time attribute.");
}
if (group.getLowerBound().isPreceding() && group.getLowerBound().isUnbounded()) {
throw new TableException(
"Python UDAF is not supported to be used in UNBOUNDED PRECEDING OVER windows.");
} else if (!group.getUpperBound().isCurrentRow()) {
throw new TableException(
"Python UDAF is not supported to be used in UNBOUNDED FOLLOWING OVER windows.");
}
Object boundValue = OverAggregateUtil.getBoundary(overSpec, group.getLowerBound());
if (boundValue instanceof BigDecimal) {
throw new TableException(
"the specific value is decimal which haven not supported yet.");
}
long precedingOffset = -1 * (long) boundValue;
Configuration pythonConfig =
CommonPythonUtil.extractPythonConfiguration(
planner.getTableConfig(), planner.getFlinkContext().getClassLoader());
OneInputTransformation<RowData, RowData> transform =
createPythonOneInputTransformation(
inputTransform,
inputRowType,
InternalTypeInfo.of(getOutputType()).toRowType(),
rowTimeIdx,
group.getAggCalls().toArray(new AggregateCall[0]),
precedingOffset,
group.isRows(),
config.getStateRetentionTime(),
TableConfigUtils.getMaxIdleStateRetentionTime(config),
pythonConfig,
config,
planner.getFlinkContext().getClassLoader());
if (CommonPythonUtil.isPythonWorkerUsingManagedMemory(
pythonConfig, planner.getFlinkContext().getClassLoader())) {
transform.declareManagedMemoryUseCaseAtSlotScope(ManagedMemoryUseCase.PYTHON);
}
// set KeyType and Selector for state
final RowDataKeySelector selector =
KeySelectorUtil.getRowDataSelector(
planner.getFlinkContext().getClassLoader(),
partitionKeys,
InternalTypeInfo.of(inputRowType));
transform.setStateKeySelector(selector);
transform.setStateKeyType(selector.getProducedType());
return transform;
}
private OneInputTransformation<RowData, RowData> createPythonOneInputTransformation(
Transformation<RowData> inputTransform,
RowType inputRowType,
RowType outputRowType,
int rowTimeIdx,
AggregateCall[] aggCalls,
long lowerBoundary,
boolean isRowsClause,
long minIdleStateRetentionTime,
long maxIdleStateRetentionTime,
Configuration pythonConfig,
ExecNodeConfig config,
ClassLoader classLoader) {
Tuple2<int[], PythonFunctionInfo[]> aggCallInfos =
CommonPythonUtil.extractPythonAggregateFunctionInfosFromAggregateCall(aggCalls);
int[] pythonUdafInputOffsets = aggCallInfos.f0;
PythonFunctionInfo[] pythonFunctionInfos = aggCallInfos.f1;
OneInputStreamOperator<RowData, RowData> pythonOperator =
getPythonOverWindowAggregateFunctionOperator(
config,
classLoader,
pythonConfig,
inputRowType,
outputRowType,
rowTimeIdx,
lowerBoundary,
isRowsClause,
pythonUdafInputOffsets,
pythonFunctionInfos,
minIdleStateRetentionTime,
maxIdleStateRetentionTime);
return ExecNodeUtil.createOneInputTransformation(
inputTransform,
createTransformationMeta(PYTHON_OVER_AGGREGATE_TRANSFORMATION, config),
pythonOperator,
InternalTypeInfo.of(outputRowType),
inputTransform.getParallelism(),
false);
}
@SuppressWarnings("unchecked")
private OneInputStreamOperator<RowData, RowData> getPythonOverWindowAggregateFunctionOperator(
ExecNodeConfig config,
ClassLoader classLoader,
Configuration pythonConfig,
RowType inputRowType,
RowType outputRowType,
int rowTiemIdx,
long lowerBoundary,
boolean isRowsClause,
int[] udafInputOffsets,
PythonFunctionInfo[] pythonFunctionInfos,
long minIdleStateRetentionTime,
long maxIdleStateRetentionTime) {
RowType userDefinedFunctionInputType =
(RowType) Projection.of(udafInputOffsets).project(inputRowType);
RowType userDefinedFunctionOutputType =
(RowType)
Projection.range(
inputRowType.getFieldCount(), outputRowType.getFieldCount())
.project(outputRowType);
GeneratedProjection generatedProjection =
ProjectionCodeGenerator.generateProjection(
new CodeGeneratorContext(config, classLoader),
"UdafInputProjection",
inputRowType,
userDefinedFunctionInputType,
udafInputOffsets);
if (isRowsClause) {
String className;
if (rowTiemIdx != -1) {
className = ARROW_PYTHON_OVER_WINDOW_ROWS_ROW_TIME_AGGREGATE_FUNCTION_OPERATOR_NAME;
} else {
className =
ARROW_PYTHON_OVER_WINDOW_ROWS_PROC_TIME_AGGREGATE_FUNCTION_OPERATOR_NAME;
}
Class<?> clazz = CommonPythonUtil.loadClass(className, classLoader);
try {
Constructor<?> ctor =
clazz.getConstructor(
Configuration.class,
long.class,
long.class,
PythonFunctionInfo[].class,
RowType.class,
RowType.class,
RowType.class,
int.class,
long.class,
GeneratedProjection.class);
return (OneInputStreamOperator<RowData, RowData>)
ctor.newInstance(
pythonConfig,
minIdleStateRetentionTime,
maxIdleStateRetentionTime,
pythonFunctionInfos,
inputRowType,
userDefinedFunctionInputType,
userDefinedFunctionOutputType,
rowTiemIdx,
lowerBoundary,
generatedProjection);
} catch (NoSuchMethodException
| InstantiationException
| IllegalAccessException
| InvocationTargetException e) {
throw new TableException(
"Python Arrow Over Rows Window Function Operator constructed failed.", e);
}
} else {
String className;
if (rowTiemIdx != -1) {
className =
ARROW_PYTHON_OVER_WINDOW_RANGE_ROW_TIME_AGGREGATE_FUNCTION_OPERATOR_NAME;
} else {
className =
ARROW_PYTHON_OVER_WINDOW_RANGE_PROC_TIME_AGGREGATE_FUNCTION_OPERATOR_NAME;
}
Class<?> clazz = CommonPythonUtil.loadClass(className, classLoader);
try {
Constructor<?> ctor =
clazz.getConstructor(
Configuration.class,
PythonFunctionInfo[].class,
RowType.class,
RowType.class,
RowType.class,
int.class,
long.class,
GeneratedProjection.class);
return (OneInputStreamOperator<RowData, RowData>)
ctor.newInstance(
pythonConfig,
pythonFunctionInfos,
inputRowType,
userDefinedFunctionInputType,
userDefinedFunctionOutputType,
rowTiemIdx,
lowerBoundary,
generatedProjection);
} catch (NoSuchMethodException
| InstantiationException
| IllegalAccessException
| InvocationTargetException e) {
throw new TableException(
"Python Arrow Over Range Window Function Operator constructed failed.", e);
}
}
}
}
| StreamExecPythonOverAggregate |
java | google__guice | core/src/com/google/inject/internal/InjectionRequestProcessor.java | {
"start": 3301,
"end": 3576
} | class ____ one of its
* subclasses, the parent class's static members will be
* injected twice.
*/
for (StaticInjection staticInjection : staticInjections) {
staticInjection.injectMembers();
}
}
/** A requested static injection. */
private | and |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/SimpleMetadataAwareAspectInstanceFactory.java | {
"start": 1078,
"end": 1921
} | class ____ extends SimpleAspectInstanceFactory
implements MetadataAwareAspectInstanceFactory {
private final AspectMetadata metadata;
/**
* Create a new SimpleMetadataAwareAspectInstanceFactory for the given aspect class.
* @param aspectClass the aspect class
* @param aspectName the aspect name
*/
public SimpleMetadataAwareAspectInstanceFactory(Class<?> aspectClass, String aspectName) {
super(aspectClass);
this.metadata = new AspectMetadata(aspectClass, aspectName);
}
@Override
public final AspectMetadata getAspectMetadata() {
return this.metadata;
}
@Override
public Object getAspectCreationMutex() {
return this;
}
@Override
protected int getOrderForAspectClass(Class<?> aspectClass) {
return OrderUtils.getOrder(aspectClass, Ordered.LOWEST_PRECEDENCE);
}
}
| SimpleMetadataAwareAspectInstanceFactory |
java | google__guava | android/guava-tests/test/com/google/common/eventbus/outside/DeepInterfaceTest.java | {
"start": 1283,
"end": 1652
} | interface ____ extends Interface1 {
@Override
@Subscribe
void declaredIn1AnnotatedIn2(Object o);
@Override
@Subscribe
void annotatedIn1And2(Object o);
@Override
@Subscribe
void annotatedIn1And2AndClass(Object o);
void declaredIn2AnnotatedInClass(Object o);
@Subscribe
void annotatedIn2(Object o);
}
static | Interface2 |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/id/enhanced/CustomNamingStrategyTests.java | {
"start": 4158,
"end": 4600
} | class ____ {
@Id
@GeneratedValue( strategy = GenerationType.SEQUENCE )
private Integer id;
@Basic
private String name;
private TheEntity() {
// for use by Hibernate
}
public TheEntity(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| TheEntity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.