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 | quarkusio__quarkus | extensions/vertx/deployment/src/test/java/io/quarkus/vertx/EventBusCodecTest.java | {
"start": 5137,
"end": 5402
} | class ____ {
@ConsumeEvent(value = "nl-pet", codec = MyPetCodec.class, local = false)
public CompletionStage<String> hello(Pet p) {
return CompletableFuture.completedFuture("Non Local Hello " + p.getName());
}
}
}
| MyNonLocalBean |
java | apache__kafka | core/src/main/java/kafka/server/handlers/DescribeTopicPartitionsRequestHandler.java | {
"start": 1879,
"end": 6057
} | class ____ {
MetadataCache metadataCache;
AuthHelper authHelper;
KafkaConfig config;
public DescribeTopicPartitionsRequestHandler(
MetadataCache metadataCache,
AuthHelper authHelper,
KafkaConfig config
) {
this.metadataCache = metadataCache;
this.authHelper = authHelper;
this.config = config;
}
public DescribeTopicPartitionsResponseData handleDescribeTopicPartitionsRequest(RequestChannel.Request abstractRequest) {
DescribeTopicPartitionsRequestData request = ((DescribeTopicPartitionsRequest) abstractRequest.loggableRequest()).data();
Set<String> topics = new HashSet<>();
boolean fetchAllTopics = request.topics().isEmpty();
DescribeTopicPartitionsRequestData.Cursor cursor = request.cursor();
String cursorTopicName = cursor != null ? cursor.topicName() : "";
if (fetchAllTopics) {
metadataCache.getAllTopics().forEach(topicName -> {
if (topicName.compareTo(cursorTopicName) >= 0) {
topics.add(topicName);
}
});
} else {
request.topics().forEach(topic -> {
String topicName = topic.name();
if (topicName.compareTo(cursorTopicName) >= 0) {
topics.add(topicName);
}
});
if (cursor != null && !topics.contains(cursor.topicName())) {
// The topic in cursor must be included in the topic list if provided.
throw new InvalidRequestException("DescribeTopicPartitionsRequest topic list should contain the cursor topic: " + cursor.topicName());
}
}
if (cursor != null && cursor.partitionIndex() < 0) {
// The partition id in cursor must be valid.
throw new InvalidRequestException("DescribeTopicPartitionsRequest cursor partition must be valid: " + cursor);
}
// Do not disclose the existence of topics unauthorized for Describe, so we've not even checked if they exist or not
Set<DescribeTopicPartitionsResponseTopic> unauthorizedForDescribeTopicMetadata = new HashSet<>();
Stream<String> authorizedTopicsStream = topics.stream().filter(topicName -> {
boolean isAuthorized = authHelper.authorize(
abstractRequest.context(), DESCRIBE, TOPIC, topicName, true, true, 1);
if (!fetchAllTopics && !isAuthorized) {
// We should not return topicId when on unauthorized error, so we return zero uuid.
unauthorizedForDescribeTopicMetadata.add(describeTopicPartitionsResponseTopic(
Errors.TOPIC_AUTHORIZATION_FAILED, topicName, Uuid.ZERO_UUID, false, List.of())
);
}
return isAuthorized;
}).sorted();
DescribeTopicPartitionsResponseData response = metadataCache.describeTopicResponse(
authorizedTopicsStream.iterator(),
abstractRequest.context().listenerName,
(String topicName) -> topicName.equals(cursorTopicName) ? cursor.partitionIndex() : 0,
Math.max(Math.min(config.maxRequestPartitionSizeLimit(), request.responsePartitionLimit()), 1),
fetchAllTopics
);
// get topic authorized operations
response.topics().forEach(topicData ->
topicData.setTopicAuthorizedOperations(authHelper.authorizedOperations(abstractRequest, new Resource(TOPIC, topicData.name()))));
response.topics().addAll(unauthorizedForDescribeTopicMetadata);
return response;
}
private DescribeTopicPartitionsResponseTopic describeTopicPartitionsResponseTopic(
Errors error,
String topic,
Uuid topicId,
Boolean isInternal,
List<DescribeTopicPartitionsResponsePartition> partitionData
) {
return new DescribeTopicPartitionsResponseTopic()
.setErrorCode(error.code())
.setName(topic)
.setTopicId(topicId)
.setIsInternal(isInternal)
.setPartitions(partitionData);
}
}
| DescribeTopicPartitionsRequestHandler |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/model/common/ConversionContext.java | {
"start": 336,
"end": 978
} | interface ____ {
/**
* Returns the target type of this conversion.
*
* @return The target type of this conversion.
*/
Type getTargetType();
/**
* Returns the date format if this conversion or built-in method is from String to a date type (e.g. {@link Date})
* or vice versa.
*
* @return The date format if this conversion or built-in method is from String to a date type. {@code null} is
* returned for other types or if not given.
*/
String getDateFormat();
String getNumberFormat();
String getLocale();
TypeFactory getTypeFactory();
}
| ConversionContext |
java | quarkusio__quarkus | extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/ApplyResolveNamesImagePolicyDecorator.java | {
"start": 228,
"end": 566
} | class ____ extends NamedResourceDecorator<PodTemplateSpecFluent<?>> {
@Override
public void andThenVisit(PodTemplateSpecFluent<?> podTemplate, ObjectMeta meta) {
podTemplate.editOrNewMetadata().addToAnnotations("alpha.image.policy.openshift.io/resolve-names", "*").endMetadata();
}
}
| ApplyResolveNamesImagePolicyDecorator |
java | apache__kafka | connect/runtime/src/main/java/org/apache/kafka/connect/runtime/WorkerSinkTask.java | {
"start": 32575,
"end": 36917
} | class ____ implements ConsumerRebalanceListener {
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
log.debug("{} Partitions assigned {}", WorkerSinkTask.this, partitions);
for (TopicPartition tp : partitions) {
long pos = consumer.position(tp);
lastCommittedOffsets.put(tp, new OffsetAndMetadata(pos));
currentOffsets.put(tp, new OffsetAndMetadata(pos));
log.debug("{} Assigned topic partition {} with offset {}", WorkerSinkTask.this, tp, pos);
}
sinkTaskMetricsGroup.assignedOffsets(currentOffsets);
boolean wasPausedForRedelivery = pausedForRedelivery;
pausedForRedelivery = wasPausedForRedelivery && !messageBatch.isEmpty();
if (pausedForRedelivery) {
// Re-pause here in case we picked up new partitions in the rebalance
pauseAll();
} else {
// If we paused everything for redelivery and all partitions for the failed deliveries have been revoked, make
// sure anything we paused that the task didn't request to be paused *and* which we still own is resumed.
// Also make sure our tracking of paused partitions is updated to remove any partitions we no longer own.
if (wasPausedForRedelivery) {
resumeAll();
}
// Ensure that the paused partitions contains only assigned partitions and repause as necessary
context.pausedPartitions().retainAll(consumer.assignment());
if (shouldPause())
pauseAll();
else if (!context.pausedPartitions().isEmpty())
consumer.pause(context.pausedPartitions());
}
updatePartitionCount();
if (partitions.isEmpty()) {
return;
}
// Instead of invoking the assignment callback on initialization, we guarantee the consumer is ready upon
// task start. Since this callback gets invoked during that initial setup before we've started the task, we
// need to guard against invoking the user's callback method during that period.
if (rebalanceException == null || rebalanceException instanceof WakeupException) {
try {
openPartitions(partitions);
// Rewind should be applied only if openPartitions succeeds.
rewind();
} catch (RuntimeException e) {
// The consumer swallows exceptions raised in the rebalance listener, so we need to store
// exceptions and rethrow when poll() returns.
rebalanceException = e;
}
}
}
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
onPartitionsRemoved(partitions, false);
}
@Override
public void onPartitionsLost(Collection<TopicPartition> partitions) {
onPartitionsRemoved(partitions, true);
}
private void onPartitionsRemoved(Collection<TopicPartition> partitions, boolean lost) {
if (taskStopped) {
log.trace("Skipping partition revocation callback as task has already been stopped");
return;
}
log.debug("{} Partitions {}: {}", WorkerSinkTask.this, lost ? "lost" : "revoked", partitions);
if (partitions.isEmpty())
return;
try {
closePartitions(partitions, lost);
sinkTaskMetricsGroup.clearOffsets(partitions);
} catch (RuntimeException e) {
// The consumer swallows exceptions raised in the rebalance listener, so we need to store
// exceptions and rethrow when poll() returns.
rebalanceException = e;
}
// Make sure we don't have any leftover data since offsets for these partitions will be reset to committed positions
messageBatch.removeIf(record -> partitions.contains(new TopicPartition(record.topic(), record.kafkaPartition())));
}
}
static | HandleRebalance |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/cascade/PersistOnLazyCollectionTests.java | {
"start": 5238,
"end": 5934
} | class ____ {
@Id
private Integer id;
private String transactionCode;
@OneToOne(cascade = CascadeType.PERSIST )
private Order order;
public Payment() {
super();
}
public Payment(Integer id, Order order, String transactionCode) {
super();
this.id = id;
this.order = order;
this.transactionCode = transactionCode;
}
public Integer getId() {
return id;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public String getTransactionCode() {
return transactionCode;
}
public void setTransactionCode(String transactionCode) {
this.transactionCode = transactionCode;
}
}
}
| Payment |
java | resilience4j__resilience4j | resilience4j-rxjava2/src/test/java/io/github/resilience4j/circuitbreaker/operator/ObserverCircuitBreakerTest.java | {
"start": 545,
"end": 3247
} | class ____ extends BaseCircuitBreakerTest {
@Test
public void shouldSubscribeToObservableJust() {
given(circuitBreaker.tryAcquirePermission()).willReturn(true);
given(circuitBreaker.getCurrentTimestamp()).willReturn(System.nanoTime());
given(circuitBreaker.getTimestampUnit()).willReturn(TimeUnit.NANOSECONDS);
Observable.just("Event 1", "Event 2")
.compose(CircuitBreakerOperator.of(circuitBreaker))
.test()
.assertResult("Event 1", "Event 2");
then(circuitBreaker).should().onSuccess(anyLong(), any(TimeUnit.class));
then(circuitBreaker).should(never())
.onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
}
@Test
public void shouldPropagateError() {
given(circuitBreaker.tryAcquirePermission()).willReturn(true);
given(circuitBreaker.getCurrentTimestamp()).willReturn(System.nanoTime());
given(circuitBreaker.getTimestampUnit()).willReturn(TimeUnit.NANOSECONDS);
Observable.error(new IOException("BAM!"))
.compose(CircuitBreakerOperator.of(circuitBreaker))
.test()
.assertSubscribed()
.assertError(IOException.class)
.assertNotComplete();
then(circuitBreaker).should()
.onError(anyLong(), any(TimeUnit.class), any(IOException.class));
then(circuitBreaker).should(never()).onSuccess(anyLong(), any(TimeUnit.class));
}
@Test
public void shouldEmitErrorWithCallNotPermittedException() {
given(circuitBreaker.tryAcquirePermission()).willReturn(false);
Observable.just("Event 1", "Event 2")
.compose(CircuitBreakerOperator.of(circuitBreaker))
.test()
.assertSubscribed()
.assertError(CallNotPermittedException.class)
.assertNotComplete();
then(circuitBreaker).should(never()).onSuccess(anyLong(), any(TimeUnit.class));
then(circuitBreaker).should(never())
.onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
}
@Test
public void shouldReleasePermissionOnCancel() {
given(circuitBreaker.tryAcquirePermission()).willReturn(true);
Observable.just(1)
.delay(1, TimeUnit.DAYS)
.compose(CircuitBreakerOperator.of(circuitBreaker))
.test()
.cancel();
then(circuitBreaker).should().releasePermission();
then(circuitBreaker).should(never())
.onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
then(circuitBreaker).should(never()).onSuccess(anyLong(), any(TimeUnit.class));
}
}
| ObserverCircuitBreakerTest |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/plan/logical/OrderBySerializationTests.java | {
"start": 546,
"end": 1504
} | class ____ extends AbstractLogicalPlanSerializationTests<OrderBy> {
@Override
protected OrderBy createTestInstance() {
Source source = randomSource();
LogicalPlan child = randomChild(0);
List<Order> orders = randomList(1, 10, OrderSerializationTests::randomOrder);
return new OrderBy(source, child, orders);
}
@Override
protected OrderBy mutateInstance(OrderBy instance) throws IOException {
LogicalPlan child = instance.child();
List<Order> orders = instance.order();
if (randomBoolean()) {
child = randomValueOtherThan(child, () -> randomChild(0));
} else {
orders = randomValueOtherThan(orders, () -> randomList(1, 10, OrderSerializationTests::randomOrder));
}
return new OrderBy(instance.source(), child, orders);
}
@Override
protected boolean alwaysEmptySource() {
return true;
}
}
| OrderBySerializationTests |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreator.java | {
"start": 1763,
"end": 2189
} | interface ____ {
/**
* Create a statement in this connection. Allows implementations to use
* PreparedStatements. The JdbcTemplate will close the created statement.
* @param con the connection used to create statement
* @return a prepared statement
* @throws SQLException there is no need to catch SQLExceptions
* that may be thrown in the implementation of this method.
* The JdbcTemplate | PreparedStatementCreator |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/testutils/statemigration/TestType.java | {
"start": 8483,
"end": 9507
} | class ____
implements TypeSerializerSnapshot<TestType> {
@Override
public int getCurrentVersion() {
return 0;
}
@Override
public void writeSnapshot(DataOutputView out) {
// do nothing
}
@Override
public void readSnapshot(
int readVersion, DataInputView in, ClassLoader userCodeClassLoader) {
// do nothing
}
@Override
public TypeSerializer<TestType> restoreSerializer() {
return new IncompatibleTestTypeSerializer();
}
@Override
public TypeSerializerSchemaCompatibility<TestType> resolveSchemaCompatibility(
TypeSerializerSnapshot<TestType> oldSerializerSnapshot) {
return TypeSerializerSchemaCompatibility.incompatible();
}
}
}
public abstract static | IncompatibleTestTypeSerializerSnapshot |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4433ForceParentSnapshotUpdateTest.java | {
"start": 1062,
"end": 2709
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that snapshot updates of parent POMs can be forced from the command line via "-U".
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-4433");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteArtifacts("org.apache.maven.its.mng4433");
verifier.addCliArgument("-s");
verifier.addCliArgument("settings.xml");
Map<String, String> filterProps = verifier.newDefaultFilterMap();
filterProps.put("@repo@", "repo-1");
verifier.filterFile("settings-template.xml", "settings.xml", filterProps);
verifier.setLogFileName("log-force-1.txt");
verifier.deleteDirectory("target");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier.verifyFilePresent("target/old.txt");
verifier.verifyFileNotPresent("target/new.txt");
filterProps.put("@repo@", "repo-2");
verifier.filterFile("settings-template.xml", "settings.xml", filterProps);
verifier.setLogFileName("log-force-2.txt");
verifier.deleteDirectory("target");
verifier.addCliArgument("-U");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier.verifyFileNotPresent("target/old.txt");
verifier.verifyFilePresent("target/new.txt");
}
}
| MavenITmng4433ForceParentSnapshotUpdateTest |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/util/ObservableToFlowabeTestSync.java | {
"start": 838,
"end": 4196
} | class ____ {
private ObservableToFlowabeTestSync() {
throw new IllegalStateException("No instances!");
}
static List<String> readAllLines(File f) {
List<String> result = new ArrayList<>();
try {
BufferedReader in = new BufferedReader(new FileReader(f));
try {
String line;
while ((line = in.readLine()) != null) {
result.add(line);
}
} finally {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}
static void list(String basepath, String basepackage) throws Exception {
File[] observables = new File(basepath + "observable/").listFiles();
int count = 0;
for (File f : observables) {
if (!f.getName().endsWith(".java")) {
continue;
}
Class<?> clazz = Class.forName(basepackage + "observable." + f.getName().replace(".java", ""));
String cn = f.getName().replace(".java", "").replace("Observable", "Flowable");
File f2 = new File(basepath + "/flowable/" + cn + ".java");
if (!f2.exists()) {
continue;
}
Class<?> clazz2 = Class.forName(basepackage + "flowable." + cn);
Set<String> methods2 = new HashSet<>();
for (Method m : clazz2.getMethods()) {
methods2.add(m.getName());
}
for (Method m : clazz.getMethods()) {
if (!methods2.contains(m.getName()) && !methods2.contains(m.getName().replace("Observable", "Flowable"))) {
count++;
System.out.println();
System.out.print("java.lang.RuntimeException: missing > ");
System.out.println(m.getName());
System.out.print(" at ");
System.out.print(clazz.getName());
System.out.print(" (");
System.out.print(clazz.getSimpleName());
System.out.print(".java:");
List<String> lines = readAllLines(f);
int j = 1;
for (int i = 1; i <= lines.size(); i++) {
if (lines.get(i - 1).contains("public void " + m.getName() + "(")) {
j = i;
}
}
System.out.print(j);
System.out.println(")");
System.out.print(" at ");
System.out.print(clazz2.getName());
System.out.print(" (");
System.out.print(clazz2.getSimpleName());
lines = readAllLines(f2);
System.out.print(".java:");
System.out.print(lines.size() - 1);
System.out.println(")");
}
}
}
System.out.println();
System.out.println(count);
}
public static void main(String[] args) throws Exception {
list("src/test/java/io/reactivex/internal/operators/", "io.reactivex.internal.operators.");
// list("src/test/java/io/reactivex/", "io.reactivex.");
}
}
| ObservableToFlowabeTestSync |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inject/guice/OverridesJavaxInjectableMethodTest.java | {
"start": 3613,
"end": 3808
} | class ____ extends TestClass3 {
@com.google.inject.Inject
public void foo() {}
}
/** jInject <- gInject */
public | TestClass5 |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineEditsViewer/OfflineEditsLoader.java | {
"start": 1473,
"end": 2346
} | class ____ {
static OfflineEditsLoader createLoader(OfflineEditsVisitor visitor,
String inputFileName, boolean xmlInput,
OfflineEditsViewer.Flags flags) throws IOException {
if (xmlInput) {
return new OfflineEditsXmlLoader(visitor, new File(inputFileName), flags);
} else {
File file = null;
EditLogInputStream elis = null;
OfflineEditsLoader loader = null;
try {
file = new File(inputFileName);
elis = new EditLogFileInputStream(file, HdfsServerConstants.INVALID_TXID,
HdfsServerConstants.INVALID_TXID, false);
loader = new OfflineEditsBinaryLoader(visitor, elis, flags);
} finally {
if ((loader == null) && (elis != null)) {
elis.close();
}
}
return loader;
}
}
}
}
| OfflineEditsLoaderFactory |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/processor/utils/TopologyGraph.java | {
"start": 1670,
"end": 7932
} | class ____ {
private final Map<ExecNode<?>, TopologyNode> nodes;
TopologyGraph(List<ExecNode<?>> roots) {
this(roots, Collections.emptySet());
}
TopologyGraph(List<ExecNode<?>> roots, Set<ExecNode<?>> boundaries) {
this.nodes = new HashMap<>();
// we first link all edges in the original exec node graph
AbstractExecNodeExactlyOnceVisitor visitor =
new AbstractExecNodeExactlyOnceVisitor() {
@Override
protected void visitNode(ExecNode<?> node) {
if (boundaries.contains(node)) {
return;
}
for (ExecEdge inputEdge : node.getInputEdges()) {
link(inputEdge.getSource(), node);
}
visitInputs(node);
}
};
roots.forEach(n -> n.accept(visitor));
}
/**
* Link an edge from `from` node to `to` node if no loop will occur after adding this edge.
* Returns if this edge is successfully added.
*/
boolean link(ExecNode<?> from, ExecNode<?> to) {
TopologyNode fromNode = getOrCreateTopologyNode(from);
TopologyNode toNode = getOrCreateTopologyNode(to);
if (canReach(toNode, fromNode)) {
// invalid edge, as `to` is the predecessor of `from`
return false;
} else {
// link `from` and `to`
fromNode.outputs.add(toNode);
toNode.inputs.add(fromNode);
return true;
}
}
/**
* Remove the edge from `from` node to `to` node. If there is no edge between them then do
* nothing.
*/
void unlink(ExecNode<?> from, ExecNode<?> to) {
TopologyNode fromNode = getOrCreateTopologyNode(from);
TopologyNode toNode = getOrCreateTopologyNode(to);
fromNode.outputs.remove(toNode);
toNode.inputs.remove(fromNode);
}
/**
* Calculate the maximum distance of the currently added nodes from the nodes without inputs.
* The smallest distance is 0 (which are exactly the nodes without inputs) and the distances of
* other nodes are the largest distances in their inputs plus 1.
*
* <p>Distance of a node is defined as the number of edges one needs to go through from the
* nodes without inputs to this node.
*/
Map<ExecNode<?>, Integer> calculateMaximumDistance() {
Map<ExecNode<?>, Integer> result = new HashMap<>();
Map<TopologyNode, Integer> inputsVisitedMap = new HashMap<>();
Queue<TopologyNode> queue = new LinkedList<>();
for (TopologyNode node : nodes.values()) {
if (node.inputs.size() == 0) {
queue.offer(node);
}
}
while (!queue.isEmpty()) {
TopologyNode node = queue.poll();
int dist = -1;
for (TopologyNode input : node.inputs) {
dist =
Math.max(
dist,
Preconditions.checkNotNull(
result.get(input.execNode),
"The distance of an input node is not calculated. This is a bug."));
}
dist++;
result.put(node.execNode, dist);
for (TopologyNode output : node.outputs) {
int inputsVisited =
inputsVisitedMap.compute(output, (k, v) -> v == null ? 1 : v + 1);
if (inputsVisited == output.inputs.size()) {
queue.offer(output);
}
}
}
return result;
}
/**
* Make the distance of node A at least as far as node B by adding edges from all inputs of node
* B to node A.
*/
void makeAsFarAs(ExecNode<?> a, ExecNode<?> b) {
TopologyNode nodeA = getOrCreateTopologyNode(a);
TopologyNode nodeB = getOrCreateTopologyNode(b);
for (TopologyNode input : nodeB.inputs) {
link(input.execNode, nodeA.execNode);
}
}
boolean canReach(ExecNode<?> from, ExecNode<?> to) {
TopologyNode fromNode = getOrCreateTopologyNode(from);
TopologyNode toNode = getOrCreateTopologyNode(to);
return canReach(fromNode, toNode);
}
private boolean canReach(TopologyNode from, TopologyNode to) {
Set<TopologyNode> visited = new HashSet<>();
visited.add(from);
Queue<TopologyNode> queue = new LinkedList<>();
queue.offer(from);
while (!queue.isEmpty()) {
TopologyNode node = queue.poll();
if (to.equals(node)) {
return true;
}
for (TopologyNode next : node.outputs) {
if (visited.contains(next)) {
continue;
}
visited.add(next);
queue.offer(next);
}
}
return false;
}
private TopologyNode getOrCreateTopologyNode(ExecNode<?> execNode) {
// NOTE: We treat different `BatchExecBoundedStreamScan`s with same `DataStream` object as
// the same
if (execNode instanceof BatchExecBoundedStreamScan) {
DataStream<?> currentStream = ((BatchExecBoundedStreamScan) execNode).getDataStream();
for (Map.Entry<ExecNode<?>, TopologyNode> entry : nodes.entrySet()) {
ExecNode<?> key = entry.getKey();
if (key instanceof BatchExecBoundedStreamScan) {
DataStream<?> existingStream =
((BatchExecBoundedStreamScan) key).getDataStream();
if (existingStream.equals(currentStream)) {
return entry.getValue();
}
}
}
TopologyNode result = new TopologyNode(execNode);
nodes.put(execNode, result);
return result;
} else {
return nodes.computeIfAbsent(execNode, k -> new TopologyNode(execNode));
}
}
/** A node in the {@link TopologyGraph}. */
private static | TopologyGraph |
java | elastic__elasticsearch | libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfigurationLoader.java | {
"start": 11117,
"end": 11401
} | class ____ implement this method to load a fully-qualified key from the preferred settings source.
* This method will be called for basic string settings (see {@link SslConfigurationKeys#getStringKeys()}).
* <p>
* The setting should be returned as a string, and this | should |
java | junit-team__junit5 | junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedClass.java | {
"start": 2887,
"end": 5778
} | class ____ the same index in
* the constructor's formal parameter list. An <em>aggregator</em> is any
* parameter of type
* {@link org.junit.jupiter.params.aggregator.ArgumentsAccessor ArgumentsAccessor}
* or any parameter annotated with
* {@link org.junit.jupiter.params.aggregator.AggregateWith @AggregateWith}.
*
* <h3>Field injection</h3>
*
* <p>Fields annotated with {@code @Parameter} must be declared according to the
* following rules.
*
* <ol>
* <li>Zero or more <em>indexed parameters</em> may be declared; each must have
* a unique index specified in its {@code @Parameter(index)} annotation. The
* index may be omitted if there is only one indexed parameter. If there are at
* least two indexed parameter declarations, there must be declarations for all
* indexes from 0 to the largest declared index.</li>
* <li>Zero or more <em>aggregators</em> may be declared; each without
* specifying an index in its {@code @Parameter} annotation.</li>
* <li>Zero or more other fields may be declared as usual as long as they're not
* annotated with {@code @Parameter}.</li>
* </ol>
*
* <p>In this context, an <em>indexed parameter</em> is an argument for a given
* index in the {@code Arguments} provided by an {@code ArgumentsProvider} that
* is injected into a field annotated with {@code @Parameter(index)}. An
* <em>aggregator</em> is any {@code @Parameter}-annotated field of type
* {@link org.junit.jupiter.params.aggregator.ArgumentsAccessor ArgumentsAccessor}
* or any field annotated with
* {@link org.junit.jupiter.params.aggregator.AggregateWith @AggregateWith}.
*
* <h2>Argument Conversion</h2>
*
* <p>{@code @Parameter}-annotated fields or constructor parameters may be
* annotated with
* {@link org.junit.jupiter.params.converter.ConvertWith @ConvertWith}
* or a corresponding composed annotation to specify an <em>explicit</em>
* {@link org.junit.jupiter.params.converter.ArgumentConverter ArgumentConverter}.
* Otherwise, JUnit Jupiter will attempt to perform an <em>implicit</em>
* conversion to the target type automatically (see the User Guide for further
* details).
*
* <h2>Lifecycle Methods</h2>
*
* <p>If you wish to execute custom code before or after each invocation of the
* parameterized class, you may declare methods annotated with
* {@link BeforeParameterizedClassInvocation @BeforeParameterizedClassInvocation}
* or {@link AfterParameterizedClassInvocation @AfterParameterizedClassInvocation}.
* This can, for example, be useful to initialize the arguments before they are
* used.
*
* <h2>Composed Annotations</h2>
*
* <p>{@code @ParameterizedClass} may also be used as a meta-annotation in
* order to create a custom <em>composed annotation</em> that inherits the
* semantics of {@code @ParameterizedClass}.
*
* <h2>Inheritance</h2>
*
* <p>This annotation is {@linkplain Inherited inherited} within | at |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/filter/factory/RemoveJsonAttributesResponseBodyGatewayFilterFactory.java | {
"start": 3880,
"end": 4606
} | class ____ {
private @Nullable List<String> fieldList;
private boolean deleteRecursively;
public boolean isDeleteRecursively() {
return deleteRecursively;
}
public FieldListConfiguration setDeleteRecursively(boolean deleteRecursively) {
this.deleteRecursively = deleteRecursively;
return this;
}
public @Nullable List<String> getFieldList() {
return fieldList;
}
public FieldListConfiguration setFieldList(List<String> fieldList) {
this.fieldList = fieldList;
return this;
}
@Override
public String toString() {
return new ToStringCreator(this).append("fieldList", fieldList)
.append("deleteRecursively", deleteRecursively)
.toString();
}
}
}
| FieldListConfiguration |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/contexts/request/propagation/ActivateRequestContextInterceptorTest.java | {
"start": 1985,
"end": 4540
} | class ____ {
InstanceHandle<SessionClient> clientHandler;
@BeforeEach
void reset() {
FakeSession.state = INIT;
clientHandler = Arc.container().instance(SessionClient.class);
}
@AfterEach
void terminate() {
clientHandler.close();
clientHandler.destroy();
}
@Test
public void testUni() throws Exception {
Assertions.assertEquals(INIT, FakeSession.getState());
FakeSession.State result = clientHandler.get().openUniSession().await().indefinitely();
// Closed in the dispose method
Assertions.assertEquals(CLOSED, FakeSession.getState());
Assertions.assertEquals(OPENED, result);
}
@Test
public void testMulti() throws Exception {
Assertions.assertEquals(INIT, FakeSession.getState());
FakeSession.State result = clientHandler.get().openMultiSession()
.toUni()
.await().indefinitely();
// Closed in the dispose method
Assertions.assertEquals(CLOSED, FakeSession.getState());
Assertions.assertEquals(OPENED, result);
}
@Test
public void testFuture() throws Exception {
Assertions.assertEquals(INIT, FakeSession.getState());
FakeSession.State result = clientHandler.get()
.openFutureSession().toCompletableFuture().join();
// Closed in the dispose method
Assertions.assertEquals(CLOSED, FakeSession.getState());
Assertions.assertEquals(OPENED, result);
}
@Test
public void testStage() throws Exception {
Assertions.assertEquals(INIT, FakeSession.getState());
FakeSession.State result = clientHandler.get().openStageSession()
.toCompletableFuture().join();
// Closed in the dispose method
Assertions.assertEquals(CLOSED, FakeSession.getState());
Assertions.assertEquals(OPENED, result);
}
@Test
public void testNonReactive() throws Exception {
Assertions.assertEquals(INIT, FakeSession.getState());
FakeSession.State result = clientHandler.get().openSession();
// Closed in the dispose method
Assertions.assertEquals(CLOSED, FakeSession.getState());
Assertions.assertEquals(OPENED, result);
}
}
@Nested
| CompletingActivateRequestContext |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullableTest.java | {
"start": 8140,
"end": 8343
} | class ____ {
Object get(Supplier<? extends Void> s) {
// BUG: Diagnostic contains: @Nullable
return s.get();
}
| LiteralNullReturnTest |
java | google__dagger | javatests/dagger/internal/codegen/FullBindingGraphValidationTest.java | {
"start": 1322,
"end": 3710
} | interface ____ {",
" @Binds Object object1(String string);",
" @Binds Object object2(Long l);",
" @Binds Number missingDependency(Integer i);",
"}");
// Make sure the error doesn't show other bindings or a dependency trace afterwards.
private static final Pattern MODULE_WITH_ERRORS_MESSAGE =
endsWithMessage(
"\033[1;31m[Dagger/DuplicateBindings]\033[0m Object is bound multiple times:",
" @Binds Object ModuleWithErrors.object1(String)",
" @Binds Object ModuleWithErrors.object2(Long)",
" in component: [ModuleWithErrors]",
"",
"======================",
"Full classname legend:",
"======================",
"ModuleWithErrors: test.ModuleWithErrors",
"========================",
"End of classname legend:",
"========================");
private static final Pattern INCLUDES_MODULE_WITH_ERRORS_MESSAGE =
endsWithMessage(
"\033[1;31m[Dagger/DuplicateBindings]\033[0m Object is bound multiple times:",
" @Binds Object ModuleWithErrors.object1(String)",
" @Binds Object ModuleWithErrors.object2(Long)",
" in component: [IncludesModuleWithErrors]",
"",
"======================",
"Full classname legend:",
"======================",
"IncludesModuleWithErrors: test.IncludesModuleWithErrors",
"ModuleWithErrors: test.ModuleWithErrors",
"========================",
"End of classname legend:",
"========================");
@Test
public void moduleWithErrors_validationTypeNone() {
CompilerTests.daggerCompiler(MODULE_WITH_ERRORS)
.compile(
subject -> {
subject.hasErrorCount(0);
subject.hasWarningCount(0);
});
}
@Test
public void moduleWithErrors_validationTypeError() {
CompilerTests.daggerCompiler(MODULE_WITH_ERRORS)
.withProcessingOptions(ImmutableMap.of("dagger.fullBindingGraphValidation", "ERROR"))
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContainingMatch(MODULE_WITH_ERRORS_MESSAGE.pattern())
.onSource(MODULE_WITH_ERRORS)
.onLineContaining(" | ModuleWithErrors |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/inference/action/GetRerankerWindowSizeAction.java | {
"start": 2214,
"end": 3079
} | class ____ extends ActionResponse {
private final int windowSize;
public Response(int windowSize) {
this.windowSize = windowSize;
}
public Response(StreamInput in) throws IOException {
this.windowSize = in.readVInt();
}
public int getWindowSize() {
return windowSize;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(windowSize);
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Response response = (Response) o;
return windowSize == response.windowSize;
}
@Override
public int hashCode() {
return Objects.hashCode(windowSize);
}
}
}
| Response |
java | spring-projects__spring-security | oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java | {
"start": 1487,
"end": 5643
} | class ____ implements BearerTokenResolver {
private static final String ACCESS_TOKEN_PARAMETER_NAME = "access_token";
private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+=*)$",
Pattern.CASE_INSENSITIVE);
private boolean allowFormEncodedBodyParameter = false;
private boolean allowUriQueryParameter = false;
private String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION;
@Override
public String resolve(final HttpServletRequest request) {
// @formatter:off
return resolveToken(
resolveFromAuthorizationHeader(request),
resolveAccessTokenFromQueryString(request),
resolveAccessTokenFromBody(request)
);
// @formatter:on
}
private static String resolveToken(String... accessTokens) {
if (accessTokens == null || accessTokens.length == 0) {
return null;
}
String accessToken = null;
for (String token : accessTokens) {
if (accessToken == null) {
accessToken = token;
}
else if (token != null) {
BearerTokenError error = BearerTokenErrors
.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
}
}
if (accessToken != null && accessToken.isBlank()) {
BearerTokenError error = BearerTokenErrors
.invalidRequest("The requested token parameter is an empty string");
throw new OAuth2AuthenticationException(error);
}
return accessToken;
}
private String resolveFromAuthorizationHeader(HttpServletRequest request) {
String authorization = request.getHeader(this.bearerTokenHeaderName);
if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) {
return null;
}
Matcher matcher = authorizationPattern.matcher(authorization);
if (!matcher.matches()) {
BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed");
throw new OAuth2AuthenticationException(error);
}
return matcher.group("token");
}
private String resolveAccessTokenFromQueryString(HttpServletRequest request) {
if (!this.allowUriQueryParameter || !HttpMethod.GET.name().equals(request.getMethod())) {
return null;
}
return resolveToken(request.getParameterValues(ACCESS_TOKEN_PARAMETER_NAME));
}
private String resolveAccessTokenFromBody(HttpServletRequest request) {
if (!this.allowFormEncodedBodyParameter
|| !MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType())
|| HttpMethod.GET.name().equals(request.getMethod())) {
return null;
}
String queryString = request.getQueryString();
if (queryString != null && queryString.contains(ACCESS_TOKEN_PARAMETER_NAME)) {
return null;
}
return resolveToken(request.getParameterValues(ACCESS_TOKEN_PARAMETER_NAME));
}
/**
* Set if transport of access token using form-encoded body parameter is supported.
* Defaults to {@code false}.
* @param allowFormEncodedBodyParameter if the form-encoded body parameter is
* supported
*/
public void setAllowFormEncodedBodyParameter(boolean allowFormEncodedBodyParameter) {
this.allowFormEncodedBodyParameter = allowFormEncodedBodyParameter;
}
/**
* Set if transport of access token using URI query parameter is supported. Defaults
* to {@code false}.
*
* The spec recommends against using this mechanism for sending bearer tokens, and
* even goes as far as stating that it was only included for completeness.
* @param allowUriQueryParameter if the URI query parameter is supported
*/
public void setAllowUriQueryParameter(boolean allowUriQueryParameter) {
this.allowUriQueryParameter = allowUriQueryParameter;
}
/**
* Set this value to configure what header is checked when resolving a Bearer Token.
* This value is defaulted to {@link HttpHeaders#AUTHORIZATION}.
*
* This allows other headers to be used as the Bearer Token source such as
* {@link HttpHeaders#PROXY_AUTHORIZATION}
* @param bearerTokenHeaderName the header to check when retrieving the Bearer Token.
* @since 5.4
*/
public void setBearerTokenHeaderName(String bearerTokenHeaderName) {
this.bearerTokenHeaderName = bearerTokenHeaderName;
}
}
| DefaultBearerTokenResolver |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ObjectsHashCodePrimitiveTest.java | {
"start": 7471,
"end": 7876
} | class ____ {
Object o = new Object();
void f() {
int y = Objects.hashCode(o);
}
}
""")
.expectUnchanged()
.doTest();
}
@Test
public void hashCodeBoxedPrimitiveNegative() {
helper
.addInputLines(
"Test.java",
"""
import java.util.Objects;
| Test |
java | apache__flink | flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/nfa/IterativeConditionsITCase.java | {
"start": 9781,
"end": 18567
} | class ____ extends IterativeCondition<Event> {
private static final long serialVersionUID = 6215754202506583964L;
@Override
public boolean filter(Event value, Context<Event> ctx) throws Exception {
if (!value.getName().equals("start")) {
return false;
}
double sum = 0.0;
for (Event event : ctx.getEventsForPattern("start")) {
sum += event.getPrice();
}
sum += value.getPrice();
return Double.compare(sum, 5.0) < 0;
}
}
@Test
public void testIterativeWithPrevPatternDependency() throws Exception {
List<StreamRecord<Event>> inputEvents = new ArrayList<>();
inputEvents.add(new StreamRecord<>(startEvent1, 1L));
inputEvents.add(new StreamRecord<>(startEvent2, 2L));
inputEvents.add(new StreamRecord<>(endEvent, 4L));
Pattern<Event, ?> pattern =
Pattern.<Event>begin("start")
.where(SimpleCondition.of(value -> value.getName().equals("start")))
.oneOrMore()
.followedBy("end")
.where(
new IterativeCondition<Event>() {
private static final long serialVersionUID =
7056763917392056548L;
@Override
public boolean filter(Event value, Context<Event> ctx)
throws Exception {
if (!value.getName().equals("end")) {
return false;
}
double sum = 0.0;
for (Event event : ctx.getEventsForPattern("start")) {
sum += event.getPrice();
}
return Double.compare(sum, 2.0) >= 0;
}
});
NFA<Event> nfa = compile(pattern, false);
List<List<Event>> resultingPatterns = feedNFA(inputEvents, nfa);
comparePatterns(
resultingPatterns,
Lists.<List<Event>>newArrayList(
Lists.newArrayList(startEvent1, startEvent2, endEvent),
Lists.newArrayList(startEvent2, endEvent)));
}
@Test
public void testIterativeWithABACPattern() throws Exception {
List<StreamRecord<Event>> inputEvents = new ArrayList<>();
inputEvents.add(new StreamRecord<>(startEvent1, 1L)); // 1
inputEvents.add(new StreamRecord<Event>(middleEvent1, 2L)); // 1
inputEvents.add(new StreamRecord<>(startEvent2, 2L)); // 2
inputEvents.add(new StreamRecord<>(startEvent3, 2L)); // 3
inputEvents.add(new StreamRecord<Event>(middleEvent2, 2L)); // 2
inputEvents.add(new StreamRecord<>(startEvent4, 2L)); // 4
inputEvents.add(new StreamRecord<Event>(middleEvent3, 2L)); // 3
inputEvents.add(new StreamRecord<Event>(middleEvent4, 2L)); // 1
inputEvents.add(new StreamRecord<>(endEvent, 4L));
Pattern<Event, ?> pattern =
Pattern.<Event>begin("start")
.where(SimpleCondition.of(value -> value.getName().equals("start")))
.followedByAny("middle1")
.subtype(SubEvent.class)
.where(SimpleCondition.of(value -> value.getName().startsWith("foo")))
.followedBy("middle2")
.where(
new IterativeCondition<Event>() {
private static final long serialVersionUID =
-1223388426808292695L;
@Override
public boolean filter(Event value, Context<Event> ctx)
throws Exception {
if (!value.getName().equals("start")) {
return false;
}
double sum = 0.0;
for (Event e : ctx.getEventsForPattern("middle2")) {
sum += e.getPrice();
}
sum += value.getPrice();
return Double.compare(sum, 5.0) <= 0;
}
})
.oneOrMore()
.followedBy("end")
.where(SimpleCondition.of(value -> value.getName().equals("end")));
NFA<Event> nfa = compile(pattern, false);
List<List<Event>> resultingPatterns = feedNFA(inputEvents, nfa);
comparePatterns(
resultingPatterns,
Lists.<List<Event>>newArrayList(
Lists.newArrayList(
startEvent1, startEvent2, startEvent3, middleEvent1, endEvent),
Lists.newArrayList(startEvent1, middleEvent1, startEvent2, endEvent),
Lists.newArrayList(startEvent1, middleEvent2, startEvent4, endEvent),
Lists.newArrayList(startEvent2, middleEvent2, startEvent4, endEvent),
Lists.newArrayList(startEvent3, middleEvent2, startEvent4, endEvent)));
}
@Test
public void testIterativeWithPrevPatternDependencyAfterBranching() throws Exception {
List<StreamRecord<Event>> inputEvents = new ArrayList<>();
inputEvents.add(new StreamRecord<>(startEvent1, 1L));
inputEvents.add(new StreamRecord<>(startEvent2, 2L));
inputEvents.add(new StreamRecord<Event>(middleEvent1, 4L));
inputEvents.add(new StreamRecord<>(startEvent3, 5L));
inputEvents.add(new StreamRecord<Event>(middleEvent2, 6L));
inputEvents.add(new StreamRecord<>(endEvent, 7L));
Pattern<Event, ?> pattern =
Pattern.<Event>begin("start")
.where(SimpleCondition.of(value -> value.getName().equals("start")))
.oneOrMore()
.followedByAny("middle1")
.subtype(SubEvent.class)
.where(SimpleCondition.of(value -> value.getName().startsWith("foo")))
.followedByAny("end")
.where(
new IterativeCondition<Event>() {
private static final long serialVersionUID =
7056763917392056548L;
@Override
public boolean filter(Event value, Context<Event> ctx)
throws Exception {
if (!value.getName().equals("end")) {
return false;
}
double sum = 0.0;
for (Event event : ctx.getEventsForPattern("start")) {
sum += event.getPrice();
}
return Double.compare(sum, 2.0) >= 0;
}
});
NFA<Event> nfa = compile(pattern, false);
List<List<Event>> resultingPatterns = feedNFA(inputEvents, nfa);
comparePatterns(
resultingPatterns,
Lists.<List<Event>>newArrayList(
Lists.newArrayList(startEvent1, startEvent2, middleEvent1, endEvent),
Lists.newArrayList(startEvent2, middleEvent1, endEvent),
Lists.newArrayList(startEvent1, startEvent2, middleEvent2, endEvent),
Lists.newArrayList(
startEvent1, startEvent2, startEvent3, middleEvent2, endEvent),
Lists.newArrayList(startEvent2, startEvent3, middleEvent2, endEvent),
Lists.newArrayList(startEvent2, middleEvent2, endEvent),
Lists.newArrayList(startEvent3, middleEvent2, endEvent)));
}
}
| MyEventIterCondition |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/fielddata/ScriptDocValues.java | {
"start": 5080,
"end": 6222
} | class ____ implements Supplier<Double> {
private final SortedNumericDoubleValues in;
private double[] values = new double[0];
private int count;
public DoublesSupplier(SortedNumericDoubleValues in) {
this.in = in;
}
@Override
public void setNextDocId(int docId) throws IOException {
if (in.advanceExact(docId)) {
resize(in.docValueCount());
for (int i = 0; i < count; i++) {
values[i] = in.nextValue();
}
} else {
resize(0);
}
}
/**
* Set the {@link #size()} and ensure that the {@link #values} array can
* store at least that many entries.
*/
private void resize(int newSize) {
count = newSize;
values = ArrayUtil.grow(values, count);
}
@Override
public Double getInternal(int index) {
return values[index];
}
@Override
public int size() {
return count;
}
}
public static | DoublesSupplier |
java | spring-projects__spring-framework | spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/RSocketExchangeBeanRegistrationAotProcessor.java | {
"start": 2728,
"end": 3375
} | class ____ implements BeanRegistrationAotContribution {
private final Set<Class<?>> rSocketExchangeInterfaces;
public AotContribution(Set<Class<?>> rSocketExchangeInterfaces) {
this.rSocketExchangeInterfaces = rSocketExchangeInterfaces;
}
@Override
public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) {
ProxyHints proxyHints = generationContext.getRuntimeHints().proxies();
for (Class<?> rSocketExchangeInterface : this.rSocketExchangeInterfaces) {
proxyHints.registerJdkProxy(AopProxyUtils.completeJdkProxyInterfaces(rSocketExchangeInterface));
}
}
}
}
| AotContribution |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsInOutDisableTimeToLiveTest.java | {
"start": 1537,
"end": 4650
} | class ____ extends AbstractJMSTest {
@Order(2)
@RegisterExtension
public static CamelContextExtension camelContextExtension = new DefaultCamelContextExtension();
protected CamelContext context;
protected ProducerTemplate template;
protected ConsumerTemplate consumer;
private final String urlTimeout = "activemq:JmsInOutDisableTimeToLiveTest.in?requestTimeout=2000";
private final String urlTimeToLiveDisabled
= "activemq:JmsInOutDisableTimeToLiveTest.in?requestTimeout=2000&disableTimeToLive=true";
@Test
public void testInOutExpired() throws Exception {
MyCoolBean cool = new MyCoolBean(consumer, template, "JmsInOutDisableTimeToLiveTest");
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:end").expectedMessageCount(0);
// setup a message that will timeout to prove the ttl is getting set
// and that the disableTimeToLive is defaulting to false
try {
template.requestBody("direct:timeout", "World 1");
fail("Should not get here, timeout expected");
} catch (CamelExecutionException e) {
cool.someBusinessLogic();
}
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testInOutDisableTimeToLive() throws Exception {
MyCoolBean cool = new MyCoolBean(consumer, template, "JmsInOutDisableTimeToLiveTest");
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:end").expectedBodiesReceived("Hello World 2");
// send a message that sets the requestTimeout to 2 secs with a
// disableTimeToLive set to true, this should timeout
// but leave the message on the queue to be processed
// by the CoolBean
try {
template.requestBody("direct:disable", "World 2");
fail("Should not get here, timeout expected");
} catch (CamelExecutionException e) {
cool.someBusinessLogic();
}
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected String getComponentName() {
return "activemq";
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:timeout")
.to(urlTimeout)
.to("mock:result");
from("direct:disable")
.to(urlTimeToLiveDisabled)
.to("mock:result");
from("activemq:JmsInOutDisableTimeToLiveTest.out")
.to("mock:end");
}
};
}
@Override
public CamelContextExtension getCamelContextExtension() {
return camelContextExtension;
}
@BeforeEach
void setUpRequirements() {
context = camelContextExtension.getContext();
template = camelContextExtension.getProducerTemplate();
consumer = camelContextExtension.getConsumerTemplate();
}
}
| JmsInOutDisableTimeToLiveTest |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java | {
"start": 9224,
"end": 10296
} | class ____ implements ConfigDataLocationResolver<TestConfigDataResource> {
private final boolean optionalResource;
TestResolver() {
this(false);
}
private TestResolver(boolean optionalResource) {
this.optionalResource = optionalResource;
}
@Override
public boolean isResolvable(ConfigDataLocationResolverContext context, ConfigDataLocation location) {
String name = getClass().getName();
name = name.substring(name.lastIndexOf("$") + 1);
return location.hasPrefix(name + ":");
}
@Override
public List<TestConfigDataResource> resolve(ConfigDataLocationResolverContext context,
ConfigDataLocation location) {
return Collections.singletonList(new TestConfigDataResource(this.optionalResource, this, location, false));
}
@Override
public List<TestConfigDataResource> resolveProfileSpecific(ConfigDataLocationResolverContext context,
ConfigDataLocation location, Profiles profiles) {
return Collections.singletonList(new TestConfigDataResource(this.optionalResource, this, location, true));
}
}
static | TestResolver |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/querycache/EntityWithCollectionReloadCacheInheritanceTest.java | {
"start": 1607,
"end": 2993
} | class ____ {
@Test
public void test(SessionFactoryScope scope) {
scope.inTransaction( session -> {
List<HighSchoolStudent> highSchoolStudents = session.createQuery(
"select s" +
" from HighSchoolStudent s left join fetch s.subjects m" +
" where s.name in :names", HighSchoolStudent.class
)
.setParameter( "names", Arrays.asList( "Brian" ) )
.setCacheable( true )
.list();
assertThat( highSchoolStudents ).hasSize( 1 );
highSchoolStudents = session.createQuery(
"select s" +
" from HighSchoolStudent s left join fetch s.subjects m" +
" where s.name in :names", HighSchoolStudent.class
)
.setParameter( "names", Arrays.asList( "Andrew", "Brian" ) )
.setCacheable( true )
.list();
assertThat( highSchoolStudents ).hasSize( 2 );
} );
}
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
HighSchoolStudent s1 = new HighSchoolStudent();
s1.setName( "Andrew" );
session.persist( s1 );
HighSchoolStudent s2 = new HighSchoolStudent();
s2.setName( "Brian" );
session.persist( s2 );
} );
}
@AfterAll
public void tearDown(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncateMappedObjects();
}
@Entity(name = "HighSchoolStudent")
static | EntityWithCollectionReloadCacheInheritanceTest |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/cdi/JpaQueryRewriterWithCdiIntegrationTests.java | {
"start": 7725,
"end": 8290
} | class ____ implements QueryRewriter {
@Override
public String rewrite(String query, Sort sort) {
return replaceAlias(query, sort);
}
}
/**
* One query rewriter function to rule them all!
*/
private static String replaceAlias(String query, Sort sort) {
String rewrittenQuery = query.replaceAll("original_user_alias", "rewritten_user_alias");
// Capture results for testing.
results.put(ORIGINAL_QUERY, query);
results.put(REWRITTEN_QUERY, rewrittenQuery);
results.put(SORT, sort.toString());
return rewrittenQuery;
}
}
| TestQueryRewriter |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/common/xcontent/XContentTypeTests.java | {
"start": 916,
"end": 8728
} | class ____ extends ESTestCase {
public void testFromJson() throws Exception {
String mediaType = "application/json";
XContentType expectedXContentType = XContentType.JSON;
assertThat(XContentType.fromMediaType(mediaType), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + "; charset=UTF-8"), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + "; charset=utf-8"), equalTo(expectedXContentType));
}
public void testFromNdJson() throws Exception {
String mediaType = "application/x-ndjson";
XContentType expectedXContentType = XContentType.JSON;
assertThat(XContentType.fromMediaType(mediaType), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + "; charset=UTF-8"), equalTo(expectedXContentType));
}
public void testFromJsonUppercase() throws Exception {
String mediaType = "application/json".toUpperCase(Locale.ROOT);
XContentType expectedXContentType = XContentType.JSON;
assertThat(XContentType.fromMediaType(mediaType), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + "; charset=UTF-8"), equalTo(expectedXContentType));
}
public void testFromYaml() throws Exception {
String mediaType = "application/yaml";
XContentType expectedXContentType = XContentType.YAML;
assertThat(XContentType.fromMediaType(mediaType), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + "; charset=UTF-8"), equalTo(expectedXContentType));
}
public void testFromSmile() throws Exception {
String mediaType = "application/smile";
XContentType expectedXContentType = XContentType.SMILE;
assertThat(XContentType.fromMediaType(mediaType), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType));
}
public void testFromCbor() throws Exception {
String mediaType = "application/cbor";
XContentType expectedXContentType = XContentType.CBOR;
assertThat(XContentType.fromMediaType(mediaType), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType));
}
public void testFromWildcard() throws Exception {
String mediaType = "application/*";
XContentType expectedXContentType = XContentType.JSON;
assertThat(XContentType.fromMediaType(mediaType), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType));
}
public void testFromWildcardUppercase() throws Exception {
String mediaType = "APPLICATION/*";
XContentType expectedXContentType = XContentType.JSON;
assertThat(XContentType.fromMediaType(mediaType), equalTo(expectedXContentType));
assertThat(XContentType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType));
}
public void testFromRubbish() throws Exception {
assertThat(XContentType.fromMediaType(null), nullValue());
expectThrows(IllegalArgumentException.class, () -> XContentType.fromMediaType(""));
expectThrows(IllegalArgumentException.class, () -> XContentType.fromMediaType("gobbly;goop"));
assertThat(XContentType.fromMediaType("text/plain"), nullValue());
}
public void testVersionedMediaType() {
String version = String.valueOf(randomNonNegativeByte());
assertThat(
XContentType.fromMediaType("application/vnd.elasticsearch+json;compatible-with=" + version),
equalTo(XContentType.VND_JSON)
);
assertThat(
XContentType.fromMediaType("application/vnd.elasticsearch+cbor;compatible-with=" + version),
equalTo(XContentType.VND_CBOR)
);
assertThat(
XContentType.fromMediaType("application/vnd.elasticsearch+smile;compatible-with=" + version),
equalTo(XContentType.VND_SMILE)
);
assertThat(
XContentType.fromMediaType("application/vnd.elasticsearch+yaml;compatible-with=" + version),
equalTo(XContentType.VND_YAML)
);
assertThat(XContentType.fromMediaType("application/json"), equalTo(XContentType.JSON));
assertThat(
XContentType.fromMediaType("application/vnd.elasticsearch+x-ndjson;compatible-with=" + version),
equalTo(XContentType.VND_JSON)
);
assertThat(
XContentType.fromMediaType("APPLICATION/VND.ELASTICSEARCH+JSON;COMPATIBLE-WITH=" + version),
equalTo(XContentType.VND_JSON)
);
assertThat(XContentType.fromMediaType("APPLICATION/JSON"), equalTo(XContentType.JSON));
}
public void testVersionParsing() {
byte version = randomNonNegativeByte();
assertThat(XContentType.parseVersion("application/vnd.elasticsearch+json;compatible-with=" + version), equalTo(version));
assertThat(XContentType.parseVersion("application/vnd.elasticsearch+cbor;compatible-with=" + version), equalTo(version));
assertThat(XContentType.parseVersion("application/vnd.elasticsearch+smile;compatible-with=" + version), equalTo(version));
assertThat(XContentType.parseVersion("application/vnd.elasticsearch+x-ndjson;compatible-with=" + version), equalTo(version));
assertThat(XContentType.parseVersion("application/json"), nullValue());
assertThat(XContentType.parseVersion("APPLICATION/VND.ELASTICSEARCH+JSON;COMPATIBLE-WITH=" + version), equalTo(version));
assertThat(XContentType.parseVersion("APPLICATION/JSON"), nullValue());
// validation is done when parsing a MediaType
assertThat(XContentType.fromMediaType("application/vnd.elasticsearch+json;compatible-with=" + version + ".0"), is(nullValue()));
assertThat(XContentType.fromMediaType("application/vnd.elasticsearch+json;compatible-with=" + version + "_sth"), nullValue());
}
public void testUnrecognizedParameters() {
// unrecognised parameters are ignored
String version = String.valueOf(randomNonNegativeByte());
assertThat(XContentType.fromMediaType("application/json;compatible-with=" + version), is(XContentType.JSON));
// TODO do not allow parsing unrecognized parameter value https://github.com/elastic/elasticsearch/issues/63080
// assertThat(XContentType.parseVersion("application/json;compatible-with=123"),
// is(nullValue()));
}
public void testParsedMediaTypeImmutability() {
ParsedMediaType xContentTypeJson = XContentType.JSON.toParsedMediaType();
assertThat(xContentTypeJson.getParameters(), is(anEmptyMap()));
ParsedMediaType parsedMediaType = ParsedMediaType.parseMediaType(XContentType.JSON, Map.of("charset", "utf-8"));
assertThat(xContentTypeJson.getParameters(), is(anEmptyMap()));
assertThat(parsedMediaType.getParameters(), equalTo(Map.of("charset", "utf-8")));
Map<String, String> parameters = new HashMap<>(Map.of("charset", "utf-8"));
parsedMediaType = ParsedMediaType.parseMediaType(XContentType.JSON, parameters);
parameters.clear();
assertThat(parsedMediaType.getParameters(), equalTo(Map.of("charset", "utf-8")));
}
}
| XContentTypeTests |
java | elastic__elasticsearch | libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/X509Field.java | {
"start": 677,
"end": 1883
} | enum ____ {
SAN_OTHERNAME_COMMONNAME("subjectAltName.otherName.commonName", true),
SAN_DNS("subjectAltName.dnsName", true);
private final String configValue;
private final boolean supportedForRestrictedTrust;
X509Field(String configValue, boolean supportedForRestrictedTrust) {
this.configValue = configValue;
this.supportedForRestrictedTrust = supportedForRestrictedTrust;
}
@Override
public String toString() {
return configValue;
}
public static X509Field parseForRestrictedTrust(String s) {
return EnumSet.allOf(X509Field.class)
.stream()
.filter(v -> v.supportedForRestrictedTrust)
.filter(v -> v.configValue.equalsIgnoreCase(s))
.findFirst()
.orElseThrow(() -> {
throw new SslConfigException(
s
+ " is not a supported x509 field for trust restrictions. "
+ "Recognised values are ["
+ EnumSet.allOf(X509Field.class).stream().map(e -> e.configValue).collect(Collectors.toSet())
+ "]"
);
});
}
}
| X509Field |
java | apache__kafka | clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetCommitCallbackInvokerTest.java | {
"start": 1751,
"end": 6316
} | class ____ {
@Mock
private ConsumerInterceptors<?, ?> consumerInterceptors;
private OffsetCommitCallbackInvoker offsetCommitCallbackInvoker;
@BeforeEach
public void setup() {
offsetCommitCallbackInvoker = new OffsetCommitCallbackInvoker(consumerInterceptors);
}
@Test
public void testMultipleUserCallbacksInvoked() {
final TopicPartition t0 = new TopicPartition("t0", 2);
Map<TopicPartition, OffsetAndMetadata> offsets1 =
Collections.singletonMap(t0, new OffsetAndMetadata(10L));
Map<TopicPartition, OffsetAndMetadata> offsets2 =
Collections.singletonMap(t0, new OffsetAndMetadata(20L));
OffsetCommitCallback callback1 = mock(OffsetCommitCallback.class);
OffsetCommitCallback callback2 = mock(OffsetCommitCallback.class);
offsetCommitCallbackInvoker.enqueueUserCallbackInvocation(callback1, offsets1, null);
offsetCommitCallbackInvoker.enqueueUserCallbackInvocation(callback2, offsets2, null);
verify(callback1, never()).onComplete(any(), any());
verify(callback2, never()).onComplete(any(), any());
offsetCommitCallbackInvoker.executeCallbacks();
InOrder inOrder = inOrder(callback1, callback2);
inOrder.verify(callback1).onComplete(offsets1, null);
inOrder.verify(callback2).onComplete(offsets2, null);
offsetCommitCallbackInvoker.executeCallbacks();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testNoOnCommitOnEmptyInterceptors() {
final TopicPartition t0 = new TopicPartition("t0", 2);
Map<TopicPartition, OffsetAndMetadata> offsets1 =
Collections.singletonMap(t0, new OffsetAndMetadata(10L));
Map<TopicPartition, OffsetAndMetadata> offsets2 =
Collections.singletonMap(t0, new OffsetAndMetadata(20L));
when(consumerInterceptors.isEmpty()).thenReturn(true);
offsetCommitCallbackInvoker.enqueueInterceptorInvocation(offsets1);
offsetCommitCallbackInvoker.enqueueInterceptorInvocation(offsets2);
offsetCommitCallbackInvoker.executeCallbacks();
verify(consumerInterceptors, never()).onCommit(any());
}
@Test
public void testOnlyInterceptors() {
final TopicPartition t0 = new TopicPartition("t0", 2);
Map<TopicPartition, OffsetAndMetadata> offsets1 =
Collections.singletonMap(t0, new OffsetAndMetadata(10L));
Map<TopicPartition, OffsetAndMetadata> offsets2 =
Collections.singletonMap(t0, new OffsetAndMetadata(20L));
when(consumerInterceptors.isEmpty()).thenReturn(false);
offsetCommitCallbackInvoker.enqueueInterceptorInvocation(offsets1);
offsetCommitCallbackInvoker.enqueueInterceptorInvocation(offsets2);
verify(consumerInterceptors, never()).onCommit(any());
offsetCommitCallbackInvoker.executeCallbacks();
InOrder inOrder = inOrder(consumerInterceptors);
inOrder.verify(consumerInterceptors).onCommit(offsets1);
inOrder.verify(consumerInterceptors).onCommit(offsets2);
offsetCommitCallbackInvoker.executeCallbacks();
inOrder.verifyNoMoreInteractions();
}
@Test
public void testMixedCallbacksInterceptorsInvoked() {
final TopicPartition t0 = new TopicPartition("t0", 2);
Map<TopicPartition, OffsetAndMetadata> offsets1 =
Collections.singletonMap(t0, new OffsetAndMetadata(10L));
Map<TopicPartition, OffsetAndMetadata> offsets2 =
Collections.singletonMap(t0, new OffsetAndMetadata(20L));
OffsetCommitCallback callback1 = mock(OffsetCommitCallback.class);
when(consumerInterceptors.isEmpty()).thenReturn(false);
offsetCommitCallbackInvoker.enqueueInterceptorInvocation(offsets1);
offsetCommitCallbackInvoker.enqueueInterceptorInvocation(offsets2);
offsetCommitCallbackInvoker.enqueueUserCallbackInvocation(callback1, offsets1, null);
verify(callback1, never()).onComplete(any(), any());
verify(consumerInterceptors, never()).onCommit(any());
offsetCommitCallbackInvoker.executeCallbacks();
InOrder inOrder = inOrder(callback1, consumerInterceptors);
inOrder.verify(consumerInterceptors).onCommit(offsets1);
inOrder.verify(consumerInterceptors).onCommit(offsets2);
inOrder.verify(callback1).onComplete(offsets1, null);
offsetCommitCallbackInvoker.executeCallbacks();
inOrder.verifyNoMoreInteractions();
}
}
| OffsetCommitCallbackInvokerTest |
java | elastic__elasticsearch | x-pack/plugin/security/qa/smoke-test-all-realms/src/javaRestTest/java/org/elasticsearch/xpack/security/authc/JwtRealmAuthIT.java | {
"start": 794,
"end": 2234
} | class ____ extends SecurityRealmSmokeTestCase {
private static final Logger LOGGER = LogManager.getLogger(JwtRealmAuthIT.class);
// Declared in build.gradle
private static final String USERNAME = "security_test_user";
private static final String HEADER_CLIENT_SECRET = "client-shared-secret-string";
private static final String HEADER_JWT = "eyJhbGciOiJIUzI1NiJ9."
+ "eyJhdWQiOiJhdWQ4Iiwic3ViIjoic2VjdXJpdHlfdGVzdF91c2VyIiwicm9sZXMiOiJbc2VjdXJpdHl"
+ "fdGVzdF9yb2xlXSIsImlzcyI6ImlzczgiLCJleHAiOjQwNzA5MDg4MDAsImlhdCI6OTQ2Njg0ODAwfQ"
+ ".YbMbSEY8j3BdE_M71np-5Q9DFHGcjZcu7D4Kk1Ji0wE";
public void testAuthenticationUsingJwtRealm() throws IOException {
final RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder()
.addHeader(
JwtRealm.HEADER_CLIENT_AUTHENTICATION,
JwtRealmSettings.HEADER_SHARED_SECRET_AUTHENTICATION_SCHEME + " " + HEADER_CLIENT_SECRET
)
.addHeader(JwtRealm.HEADER_END_USER_AUTHENTICATION, JwtRealm.HEADER_END_USER_AUTHENTICATION_SCHEME + " " + HEADER_JWT);
final Map<String, Object> authenticate = super.authenticate(options);
assertUsername(authenticate, USERNAME);
assertRealm(authenticate, "jwt", "jwt8");
assertRoles(authenticate); // empty list
assertNoApiKeyInfo(authenticate, Authentication.AuthenticationType.REALM);
}
}
| JwtRealmAuthIT |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/monitor/StatusInfo.java | {
"start": 1060,
"end": 1707
} | enum ____ {
HEALTHY,
UNHEALTHY
}
public String getInfo() {
return info;
}
public Status getStatus() {
return status;
}
private static Status readStatus(StreamInput in) throws IOException {
String statusString = in.readString();
return Status.valueOf(statusString);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(status == null ? null : status.name());
out.writeString(info);
}
@Override
public String toString() {
return "status[" + status + "]" + ", info[" + info + "]";
}
}
| Status |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/writing/ComponentRequirementExpressions.java | {
"start": 5461,
"end": 7062
} | class ____ implements ComponentRequirementExpression {
final ComponentRequirement componentRequirement;
private final Supplier<MemberSelect> field = memoize(this::createField);
private AbstractField(ComponentRequirement componentRequirement) {
this.componentRequirement = checkNotNull(componentRequirement);
}
@Override
public XCodeBlock getExpression(XClassName requestingClass) {
return field.get().getExpressionFor(requestingClass);
}
private MemberSelect createField() {
String fieldName = componentShard.getUniqueFieldName(componentRequirement.variableName());
Nullability nullability = componentRequirement.getNullability();
XTypeName fieldType =
asNullableTypeName(
componentRequirement.type().asTypeName(), nullability, compilerOptions);
XPropertySpec field =
XPropertySpecs.builder(fieldName, fieldType, PRIVATE, FINAL)
.addAnnotationNames(nullability.nonTypeUseNullableAnnotations())
.build();
componentShard.addField(COMPONENT_REQUIREMENT_FIELD, field);
componentShard.addComponentRequirementInitialization(fieldInitialization(field));
return MemberSelect.localField(componentShard, fieldName);
}
/** Returns the {@link XCodeBlock} that initializes the component field during construction. */
abstract XCodeBlock fieldInitialization(XPropertySpec componentField);
}
/**
* A {@link ComponentRequirementExpression} for {@link ComponentRequirement}s that can be
* instantiated by the component (i.e. a static | AbstractField |
java | apache__rocketmq | test/src/test/java/org/apache/rocketmq/test/lmq/TestBenchLmqStore.java | {
"start": 2741,
"end": 5817
} | class ____ {
@Test
public void test() throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
System.setProperty("sendThreadNum", "1");
System.setProperty("pullConsumerNum", "1");
System.setProperty("consumerThreadNum", "1");
BenchLmqStore.defaultMQProducer = mock(DefaultMQProducer.class);
SendResult sendResult = new SendResult();
when(BenchLmqStore.defaultMQProducer.send(any(Message.class))).thenReturn(sendResult);
BenchLmqStore.doSend();
Thread.sleep(100L);
//verify(BenchLmqStore.defaultMQProducer, atLeastOnce()).send(any(Message.class));
BenchLmqStore.defaultMQPullConsumers = new DefaultMQPullConsumer[1];
BenchLmqStore.defaultMQPullConsumers[0] = mock(DefaultMQPullConsumer.class);
BenchLmqStore.doPull(new ConcurrentHashMap<>(), new MessageQueue(), 1L);
verify(BenchLmqStore.defaultMQPullConsumers[0], atLeastOnce()).pullBlockIfNotFound(any(MessageQueue.class), anyString(), anyLong(), anyInt(), any(
PullCallback.class));
}
@Test
public void testOffset() throws RemotingException, InterruptedException, MQClientException, MQBrokerException, IllegalAccessException {
System.setProperty("sendThreadNum", "1");
DefaultMQPullConsumer defaultMQPullConsumer = mock(DefaultMQPullConsumer.class);
BenchLmqStore.defaultMQPullConsumers = new DefaultMQPullConsumer[1];
BenchLmqStore.defaultMQPullConsumers[0] = defaultMQPullConsumer;
DefaultMQPullConsumerImpl defaultMQPullConsumerImpl = mock(DefaultMQPullConsumerImpl.class);
when(defaultMQPullConsumer.getDefaultMQPullConsumerImpl()).thenReturn(defaultMQPullConsumerImpl);
RebalanceImpl rebalanceImpl = mock(RebalanceImpl.class);
when(defaultMQPullConsumerImpl.getRebalanceImpl()).thenReturn(rebalanceImpl);
MQClientInstance mqClientInstance = mock(MQClientInstance.class);
when(rebalanceImpl.getmQClientFactory()).thenReturn(mqClientInstance);
MQClientAPIImpl mqClientAPI = mock(MQClientAPIImpl.class);
when(mqClientInstance.getMQClientAPIImpl()).thenReturn(mqClientAPI);
TopicRouteData topicRouteData = new TopicRouteData();
HashMap<Long, String> brokerAddrs = new HashMap<>();
brokerAddrs.put(MixAll.MASTER_ID, "test");
List<BrokerData> brokerData = Collections.singletonList(new BrokerData("test", "test", brokerAddrs));
topicRouteData.setBrokerDatas(brokerData);
FieldUtils.writeStaticField(BenchLmqStore.class, "lmqTopic", "test", true);
when(mqClientAPI.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(topicRouteData);
BenchLmqStore.doBenchOffset();
Thread.sleep(100L);
verify(mqClientAPI, atLeastOnce()).queryConsumerOffset(anyString(), any(QueryConsumerOffsetRequestHeader.class), anyLong());
verify(mqClientAPI, atLeastOnce()).updateConsumerOffset(anyString(), any(UpdateConsumerOffsetRequestHeader.class), anyLong());
}
}
| TestBenchLmqStore |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/unit/Processors.java | {
"start": 1143,
"end": 6614
} | class ____ implements Writeable, Comparable<Processors>, ToXContentFragment {
public static final Processors ZERO = new Processors(0.0);
public static final Processors MAX_PROCESSORS = new Processors(Double.MAX_VALUE);
public static final TransportVersion FLOAT_PROCESSORS_SUPPORT_TRANSPORT_VERSION = TransportVersions.V_8_3_0;
public static final TransportVersion DOUBLE_PROCESSORS_SUPPORT_TRANSPORT_VERSION = TransportVersions.V_8_5_0;
static final int NUMBER_OF_DECIMAL_PLACES = 5;
private static final double MIN_REPRESENTABLE_PROCESSORS = 1E-5;
private final double count;
private Processors(double count) {
// Avoid rounding up to MIN_REPRESENTABLE_PROCESSORS when 0 processors are used
if (count == 0.0) {
this.count = count;
} else {
this.count = Math.max(
MIN_REPRESENTABLE_PROCESSORS,
new BigDecimal(count).setScale(NUMBER_OF_DECIMAL_PLACES, RoundingMode.HALF_UP).doubleValue()
);
}
}
@Nullable
public static Processors of(Double count) {
if (count == null) {
return null;
}
if (validNumberOfProcessors(count) == false) {
throw new IllegalArgumentException("processors must be a positive number; provided [" + count + "]");
}
return new Processors(count);
}
public static Processors readFrom(StreamInput in) throws IOException {
final double processorCount;
if (in.getTransportVersion().before(FLOAT_PROCESSORS_SUPPORT_TRANSPORT_VERSION)) {
processorCount = in.readInt();
} else if (in.getTransportVersion().before(DOUBLE_PROCESSORS_SUPPORT_TRANSPORT_VERSION)) {
processorCount = in.readFloat();
} else {
processorCount = in.readDouble();
}
return new Processors(processorCount);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
if (out.getTransportVersion().before(FLOAT_PROCESSORS_SUPPORT_TRANSPORT_VERSION)) {
assert hasDecimals() == false;
out.writeInt((int) count);
} else if (out.getTransportVersion().before(DOUBLE_PROCESSORS_SUPPORT_TRANSPORT_VERSION)) {
out.writeFloat((float) count);
} else {
out.writeDouble(count);
}
}
@Nullable
public static Processors fromXContent(XContentParser parser) throws IOException {
final double count = parser.doubleValue();
if (validNumberOfProcessors(count) == false) {
throw new IllegalArgumentException(
format(Locale.ROOT, "Only a positive number of [%s] are allowed and [%f] was provided", parser.currentName(), count)
);
}
return new Processors(count);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.value(count);
}
public Processors plus(Processors other) {
final double newProcessorCount = count + other.count;
if (Double.isFinite(newProcessorCount) == false) {
throw new ArithmeticException("Unable to add [" + this + "] and [" + other + "] the resulting value overflows");
}
return new Processors(newProcessorCount);
}
public Processors multiply(int value) {
if (value <= 0) {
throw new IllegalArgumentException("Processors cannot be multiplied by a negative number");
}
final double newProcessorCount = count * value;
if (Double.isFinite(newProcessorCount) == false) {
throw new ArithmeticException("Unable to multiply [" + this + "] by [" + value + "] the resulting value overflows");
}
return new Processors(newProcessorCount);
}
public double count() {
return count;
}
public int roundUp() {
return (int) Math.ceil(count);
}
public int roundDown() {
return Math.max(1, (int) Math.floor(count));
}
private static boolean validNumberOfProcessors(double processors) {
return Double.isFinite(processors) && processors > 0.0;
}
public boolean hasDecimals() {
return ((int) count) != Math.ceil(count);
}
@Override
public int compareTo(Processors o) {
return Double.compare(count, o.count);
}
public static boolean equalsOrCloseTo(Processors a, Processors b) {
return (a == b) || (a != null && (a.equals(b) || a.closeToAsFloat(b)));
}
private boolean closeToAsFloat(Processors b) {
if (b == null) {
return false;
}
float floatCount = (float) count;
float otherFloatCount = (float) b.count;
float maxError = Math.max(Math.ulp(floatCount), Math.ulp(otherFloatCount)) + (float) MIN_REPRESENTABLE_PROCESSORS;
return Float.isFinite(floatCount) && Float.isFinite(otherFloatCount) && (Math.abs(floatCount - otherFloatCount) < maxError);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Processors that = (Processors) o;
return Double.compare(that.count, count) == 0;
}
@Override
public int hashCode() {
return Objects.hash(count);
}
@Override
public String toString() {
return Double.toString(count);
}
}
| Processors |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/inference/chunking/WordBoundaryChunkerTests.java | {
"start": 714,
"end": 15515
} | class ____ extends ESTestCase {
@SuppressWarnings("checkstyle:linelength")
public static final String TEST_TEXT =
"Word segmentation is the problem of dividing a string of written language into its component words.\n"
+ "In English and many other languages using some form of the Latin alphabet, the space is a good approximation of a word divider "
+ "(word delimiter), although this concept has limits because of the variability with which languages emically regard collocations "
+ "and compounds. Many English compound nouns are variably written (for example, ice box = ice-box = icebox; pig sty = pig-sty = "
+ "pigsty) with a corresponding variation in whether speakers think of them as noun phrases or single nouns; there are trends in "
+ "how norms are set, such as that open compounds often tend eventually to solidify by widespread convention, but variation remains"
+ " systemic. In contrast, German compound nouns show less orthographic variation, with solidification being a stronger norm.";
public static final String[] MULTI_LINGUAL = new String[] {
"Građevne strukture Mesa Verde dokaz su akumuliranog znanja i vještina koje su se stoljećima prenosile generacijama civilizacije"
+ " Anasazi. Vrhunce svojih dosega ostvarili su u 12. i 13. stoljeću, kada su sagrađene danas najpoznatije građevine na "
+ "liticama. Zidali su obrađenim pješčenjakom, tvrđim kamenom oblikovanim do veličine štruce kruha. Kao žbuku između ciglā "
+ "stavljali su glinu razmočenu vodom. Tim su materijalom gradili prostorije veličine do 6 četvornih metara. U potkrovljima "
+ "su skladištili žitarice i druge plodine, dok su kive - ceremonijalne prostorije - gradili ispred soba, ali ukopane u zemlju,"
+ " nešto poput današnjih podruma. Kiva je bila vrhunski dizajnirana prostorija okruglog oblika s prostorom za vatru zimi te s"
+ " dovodom hladnog zraka za klimatizaciju ljeti. U zidane konstrukcije stavljali su i lokalno posječena stabla, što današnjim"
+ " arheolozima pomaže u preciznom datiranju nastanka pojedine građevine metodom dendrokronologije. Ta stabla pridonose i"
+ " teoriji o mogućem konačnom slomu ondašnjeg društva. Nakon što su, tijekom nekoliko stoljeća, šume do kraja srušene, a "
+ "njihova obnova zbog sušne klime traje i po 200 godina, nije proteklo puno vremena do konačnog urušavanja civilizacije, "
+ "koja se, na svojem vrhuncu osjećala nepobjedivom. 90 % sagrađenih naseobina ispod stijena ima do deset prostorija. ⅓ od "
+ "ukupnog broja sagrađenih kuća ima jednu ili dvije kamene prostorije",
"Histoarysk wie in acre in stik lân dat 40 roeden (oftewol 1 furlong of ⅛ myl of 660 foet) lang wie, en 4 roeden (of 66 foet) "
+ "breed. Men is fan tinken dat dat likernôch de grûnmjitte wie dy't men mei in jok oksen yn ien dei beploegje koe.",
"創業当初の「太平洋化学工業社」から1959年太平洋化学工業株式会社へ、1987年には太平洋化学㈱に社名を変更。 1990年以降、海外拠点を増やし本格的な国際進出を始動。"
+ " 創業者がつくりあげた化粧品会社を世界企業へと成長させるべく2002年3月英文社名AMOREPACIFICに改めた。",
"۱۔ ھن شق جي مطابق قادياني گروھ يا لاھوري گروھ جي ڪنھن رڪن کي جيڪو پاڻ کي 'احمدي' يا ڪنھن ٻي نالي سان پڪاري جي لاءِ ممنوع قرار "
+ "ڏنو ويو آھي تہ ھو (الف) ڳالھائي، لکي يا ڪنھن ٻي طريقي سان ڪنھن خليفي يا آنحضور ﷺ جي ڪنھن صحابي کان علاوہڍه ڪنھن کي امير"
+ " المومنين يا"
+ " خليفہ المومنين يا خليفہ المسلمين يا صحابی يا رضي الله عنه چئي۔ (ب) آنحضور ﷺ جي گھروارين کان علاوه ڪنھن کي ام المومنين "
+ "چئي۔ (ج) آنحضور ﷺ جي خاندان جي اھل بيت کان علاوہڍه ڪنھن کي اھل بيت چئي۔ (د) پنھنجي عبادت گاھ کي مسجد چئي۔" };
public static final int NUM_WORDS_IN_TEST_TEXT;
static {
var wordIterator = BreakIterator.getWordInstance(Locale.ROOT);
wordIterator.setText(TEST_TEXT);
int wordCount = 0;
while (wordIterator.next() != BreakIterator.DONE) {
wordCount++;
}
NUM_WORDS_IN_TEST_TEXT = wordCount;
}
/**
* Utility method for testing.
* Use the chunk functions that return offsets where possible
*/
List<String> textChunks(WordBoundaryChunker chunker, String input, int chunkSize, int overlap) {
var chunkPositions = chunker.chunk(input, chunkSize, overlap);
return chunkPositions.stream().map(p -> input.substring(p.start(), p.end())).collect(Collectors.toList());
}
public void testSingleSplit() {
var chunker = new WordBoundaryChunker();
var chunks = textChunks(chunker, TEST_TEXT, 10_000, 0);
assertThat(chunks, hasSize(1));
assertEquals(TEST_TEXT, chunks.get(0));
}
public void testChunkSizeOnWhiteSpaceNoOverlap() {
var numWhiteSpaceSeparatedWords = TEST_TEXT.split("\\s+").length;
var chunker = new WordBoundaryChunker();
for (var chunkSize : new int[] { 10, 20, 100, 300 }) {
var chunks = chunker.chunk(TEST_TEXT, chunkSize, 0);
int expectedNumChunks = (numWhiteSpaceSeparatedWords + chunkSize - 1) / chunkSize;
assertThat("chunk size= " + chunkSize, chunks, hasSize(expectedNumChunks));
}
}
public void testMultilingual() {
var chunker = new WordBoundaryChunker();
for (var input : MULTI_LINGUAL) {
var chunks = chunker.chunk(input, 10, 0);
assertTrue(chunks.size() > 1);
}
}
public void testNumberOfChunks() {
for (int numWords : new int[] { 10, 22, 50, 73, 100 }) {
var sb = new StringBuilder();
for (int i = 0; i < numWords; i++) {
sb.append(i).append(' ');
}
var whiteSpacedText = sb.toString();
assertExpectedNumberOfChunks(whiteSpacedText, numWords, 10, 4);
assertExpectedNumberOfChunks(whiteSpacedText, numWords, 10, 2);
assertExpectedNumberOfChunks(whiteSpacedText, numWords, 20, 4);
assertExpectedNumberOfChunks(whiteSpacedText, numWords, 20, 10);
}
}
public void testNumberOfChunksWithWordBoundaryChunkingSettings() {
for (int numWords : new int[] { 10, 22, 50, 73, 100 }) {
var sb = new StringBuilder();
for (int i = 0; i < numWords; i++) {
sb.append(i).append(' ');
}
var whiteSpacedText = sb.toString();
assertExpectedNumberOfChunksWithWordBoundaryChunkingSettings(
whiteSpacedText,
numWords,
new WordBoundaryChunkingSettings(10, 4)
);
assertExpectedNumberOfChunksWithWordBoundaryChunkingSettings(
whiteSpacedText,
numWords,
new WordBoundaryChunkingSettings(10, 2)
);
assertExpectedNumberOfChunksWithWordBoundaryChunkingSettings(
whiteSpacedText,
numWords,
new WordBoundaryChunkingSettings(20, 4)
);
assertExpectedNumberOfChunksWithWordBoundaryChunkingSettings(
whiteSpacedText,
numWords,
new WordBoundaryChunkingSettings(20, 10)
);
}
}
public void testInvalidChunkingSettingsProvided() {
ChunkingSettings chunkingSettings1 = new SentenceBoundaryChunkingSettings(randomIntBetween(20, 300), 0);
assertThrows(IllegalArgumentException.class, () -> { new WordBoundaryChunker().chunk(TEST_TEXT, chunkingSettings1); });
ChunkingSettings chunkingSettings2 = NoneChunkingSettings.INSTANCE;
assertThrows(IllegalArgumentException.class, () -> { new WordBoundaryChunker().chunk(TEST_TEXT, chunkingSettings2); });
}
public void testWindowSpanningWithOverlapNumWordsInOverlapSection() {
int chunkSize = 10;
int windowSize = 3;
for (int numWords : new int[] { 7, 8, 9, 10 }) {
var sb = new StringBuilder();
for (int i = 0; i < numWords; i++) {
sb.append(i).append(' ');
}
var chunks = new WordBoundaryChunker().chunk(sb.toString(), chunkSize, windowSize);
assertEquals("numWords= " + numWords, 1, chunks.size());
}
var sb = new StringBuilder();
for (int i = 0; i < 11; i++) {
sb.append(i).append(' ');
}
var chunks = new WordBoundaryChunker().chunk(sb.toString(), chunkSize, windowSize);
assertEquals(2, chunks.size());
}
public void testWindowSpanningWords() {
int numWords = randomIntBetween(4, 120);
var input = new StringBuilder();
for (int i = 0; i < numWords; i++) {
input.append(i).append(' ');
}
var whiteSpacedText = input.toString().stripTrailing();
var chunks = textChunks(new WordBoundaryChunker(), whiteSpacedText, 20, 10);
assertChunkContents(chunks, numWords, 20, 10);
chunks = textChunks(new WordBoundaryChunker(), whiteSpacedText, 10, 4);
assertChunkContents(chunks, numWords, 10, 4);
chunks = textChunks(new WordBoundaryChunker(), whiteSpacedText, 15, 3);
assertChunkContents(chunks, numWords, 15, 3);
}
private void assertChunkContents(List<String> chunks, int numWords, int windowSize, int overlap) {
int start = 0;
int chunkIndex = 0;
int newWordsPerWindow = windowSize - overlap;
boolean reachedEnd = false;
while (reachedEnd == false) {
var sb = new StringBuilder();
// the trailing whitespace from the previous chunk is
// included in this chunk
if (chunkIndex > 0) {
sb.append(" ");
}
int end = Math.min(start + windowSize, numWords);
for (int i = start; i < end; i++) {
sb.append(i).append(' ');
}
// delete the trailing whitespace
sb.deleteCharAt(sb.length() - 1);
assertEquals("numWords= " + numWords, sb.toString(), chunks.get(chunkIndex));
reachedEnd = end == numWords;
start += newWordsPerWindow;
chunkIndex++;
}
assertEquals("numWords= " + numWords, chunks.size(), chunkIndex);
}
public void testWindowSpanning_TextShorterThanWindow() {
var sb = new StringBuilder();
for (int i = 0; i < 8; i++) {
sb.append(i).append(' ');
}
// window size is > num words
var chunks = new WordBoundaryChunker().chunk(sb.toString(), 10, 5);
assertThat(chunks, hasSize(1));
}
public void testEmptyString() {
var chunks = textChunks(new WordBoundaryChunker(), "", 10, 5);
assertThat(chunks.toString(), chunks, contains(""));
}
public void testWhitespace() {
var chunks = textChunks(new WordBoundaryChunker(), " ", 10, 5);
assertThat(chunks, contains(" "));
}
public void testBlankString() {
var chunks = textChunks(new WordBoundaryChunker(), " ", 100, 10);
assertThat(chunks, hasSize(1));
assertThat(chunks.get(0), Matchers.is(" "));
}
public void testSingleChar() {
var chunks = textChunks(new WordBoundaryChunker(), " b", 100, 10);
assertThat(chunks, Matchers.contains(" b"));
chunks = textChunks(new WordBoundaryChunker(), "b", 100, 10);
assertThat(chunks, Matchers.contains("b"));
chunks = textChunks(new WordBoundaryChunker(), ". ", 100, 10);
assertThat(chunks, Matchers.contains(". "));
chunks = textChunks(new WordBoundaryChunker(), " , ", 100, 10);
assertThat(chunks, Matchers.contains(" , "));
chunks = textChunks(new WordBoundaryChunker(), " ,", 100, 10);
assertThat(chunks, Matchers.contains(" ,"));
}
public void testSingleCharRepeated() {
var input = "a".repeat(32_000);
var chunks = textChunks(new WordBoundaryChunker(), input, 100, 10);
assertThat(chunks, Matchers.contains(input));
}
public void testPunctuation() {
int chunkSize = 1;
var chunks = textChunks(new WordBoundaryChunker(), "Comma, separated", chunkSize, 0);
assertThat(chunks, contains("Comma", ", separated"));
chunks = textChunks(new WordBoundaryChunker(), "Mme. Thénardier", chunkSize, 0);
assertThat(chunks, contains("Mme", ". Thénardier"));
chunks = textChunks(new WordBoundaryChunker(), "Won't you chunk", chunkSize, 0);
assertThat(chunks, contains("Won't", " you", " chunk"));
chunkSize = 10;
chunks = textChunks(new WordBoundaryChunker(), "Won't you chunk", chunkSize, 0);
assertThat(chunks, contains("Won't you chunk"));
}
private void assertExpectedNumberOfChunksWithWordBoundaryChunkingSettings(
String input,
int numWords,
WordBoundaryChunkingSettings chunkingSettings
) {
var chunks = new WordBoundaryChunker().chunk(input, chunkingSettings);
int expected = expectedNumberOfChunks(numWords, chunkingSettings.maxChunkSize(), chunkingSettings.overlap());
assertEquals(expected, chunks.size());
}
private void assertExpectedNumberOfChunks(String input, int numWords, int windowSize, int overlap) {
var chunks = new WordBoundaryChunker().chunk(input, windowSize, overlap);
int expected = expectedNumberOfChunks(numWords, windowSize, overlap);
assertEquals(expected, chunks.size());
}
private int expectedNumberOfChunks(int numWords, int windowSize, int overlap) {
if (numWords < windowSize) {
return 1;
}
// the first chunk has windowSize words, because of overlap
// the subsequent will consume fewer new words
int wordsRemainingAfterFirstChunk = numWords - windowSize;
int newWordsPerWindow = windowSize - overlap;
int numberOfFollowingChunks = (wordsRemainingAfterFirstChunk + newWordsPerWindow - 1) / newWordsPerWindow;
// the +1 accounts for the first chunk
return 1 + numberOfFollowingChunks;
}
public void testInvalidParams() {
var chunker = new WordBoundaryChunker();
var e = expectThrows(IllegalArgumentException.class, () -> chunker.chunk("not evaluated", 4, 10));
assertThat(e.getMessage(), containsString("Invalid chunking parameters, overlap [10] must be < chunk size / 2 [4 / 2 = 2]"));
e = expectThrows(IllegalArgumentException.class, () -> chunker.chunk("not evaluated", 10, 6));
assertThat(e.getMessage(), containsString("Invalid chunking parameters, overlap [6] must be < chunk size / 2 [10 / 2 = 5]"));
}
}
| WordBoundaryChunkerTests |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAccessor.java | {
"start": 949,
"end": 1378
} | interface ____ {
ScopeModel getScopeModel();
default FrameworkModel getFrameworkModel() {
return ScopeModelUtil.getFrameworkModel(getScopeModel());
}
default ApplicationModel getApplicationModel() {
return ScopeModelUtil.getApplicationModel(getScopeModel());
}
default ModuleModel getModuleModel() {
return ScopeModelUtil.getModuleModel(getScopeModel());
}
}
| ScopeModelAccessor |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/mixed/MaybeFlatMapPublisher.java | {
"start": 1890,
"end": 4032
} | class ____<T, R>
extends AtomicReference<Subscription>
implements FlowableSubscriber<R>, MaybeObserver<T>, Subscription {
private static final long serialVersionUID = -8948264376121066672L;
final Subscriber<? super R> downstream;
final Function<? super T, ? extends Publisher<? extends R>> mapper;
Disposable upstream;
final AtomicLong requested;
FlatMapPublisherSubscriber(Subscriber<? super R> downstream, Function<? super T, ? extends Publisher<? extends R>> mapper) {
this.downstream = downstream;
this.mapper = mapper;
this.requested = new AtomicLong();
}
@Override
public void onNext(R t) {
downstream.onNext(t);
}
@Override
public void onError(Throwable t) {
downstream.onError(t);
}
@Override
public void onComplete() {
downstream.onComplete();
}
@Override
public void request(long n) {
SubscriptionHelper.deferredRequest(this, requested, n);
}
@Override
public void cancel() {
upstream.dispose();
SubscriptionHelper.cancel(this);
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(upstream, d)) {
this.upstream = d;
downstream.onSubscribe(this);
}
}
@Override
public void onSuccess(T t) {
Publisher<? extends R> p;
try {
p = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher");
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
downstream.onError(ex);
return;
}
if (get() != SubscriptionHelper.CANCELLED) {
p.subscribe(this);
}
}
@Override
public void onSubscribe(Subscription s) {
SubscriptionHelper.deferredSetOnce(this, requested, s);
}
}
}
| FlatMapPublisherSubscriber |
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/capacity/placement/MappingRuleCreator.java | {
"start": 2413,
"end": 8581
} | class ____ {
private static final String ALL_USER = "*";
private static Logger LOG = LoggerFactory.getLogger(MappingRuleCreator.class);
public MappingRulesDescription getMappingRulesFromJsonFile(String filePath)
throws IOException {
byte[] fileContents = Files.readAllBytes(Paths.get(filePath));
return getMappingRulesFromJson(fileContents);
}
MappingRulesDescription getMappingRulesFromJson(byte[] contents)
throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(contents, MappingRulesDescription.class);
}
MappingRulesDescription getMappingRulesFromJson(String contents)
throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(contents, MappingRulesDescription.class);
}
public List<MappingRule> getMappingRulesFromFile(String jsonPath)
throws IOException {
MappingRulesDescription desc = getMappingRulesFromJsonFile(jsonPath);
return getMappingRules(desc);
}
public List<MappingRule> getMappingRulesFromString(String json)
throws IOException {
MappingRulesDescription desc = getMappingRulesFromJson(json);
return getMappingRules(desc);
}
@VisibleForTesting
List<MappingRule> getMappingRules(MappingRulesDescription rules) {
List<MappingRule> mappingRules = new ArrayList<>();
for (Rule rule : rules.getRules()) {
checkMandatoryParameters(rule);
MappingRuleMatcher matcher = createMatcher(rule);
MappingRuleAction action = createAction(rule);
setFallbackToAction(rule, action);
MappingRule mappingRule = new MappingRule(matcher, action);
mappingRules.add(mappingRule);
}
return mappingRules;
}
private MappingRuleMatcher createMatcher(Rule rule) {
String matches = rule.getMatches();
Type type = rule.getType();
MappingRuleMatcher matcher = null;
switch (type) {
case USER:
if (ALL_USER.equals(matches)) {
matcher = MappingRuleMatchers.createAllMatcher();
} else {
matcher = MappingRuleMatchers.createUserMatcher(matches);
}
break;
case GROUP:
checkArgument(!ALL_USER.equals(matches), "Cannot match '*' for groups");
matcher = MappingRuleMatchers.createUserGroupMatcher(matches);
break;
case APPLICATION:
matcher = MappingRuleMatchers.createApplicationNameMatcher(matches);
break;
default:
throw new IllegalArgumentException("Unknown type: " + type);
}
return matcher;
}
private MappingRuleAction createAction(Rule rule) {
Policy policy = rule.getPolicy();
String queue = rule.getParentQueue();
boolean create;
if (rule.getCreate() == null) {
LOG.debug("Create flag is not set for rule {},"
+ "using \"true\" as default", rule);
create = true;
} else {
create = rule.getCreate();
}
MappingRuleAction action = null;
switch (policy) {
case DEFAULT_QUEUE:
action = MappingRuleActions.createPlaceToDefaultAction();
break;
case REJECT:
action = MappingRuleActions.createRejectAction();
break;
case PRIMARY_GROUP:
action = MappingRuleActions.createPlaceToQueueAction(
getTargetQueue(queue, "%primary_group"), create);
break;
case SECONDARY_GROUP:
action = MappingRuleActions.createPlaceToQueueAction(
getTargetQueue(queue, "%secondary_group"), create);
break;
case PRIMARY_GROUP_USER:
action = MappingRuleActions.createPlaceToQueueAction(
getTargetQueue(rule.getParentQueue(),
"%primary_group.%user"), create);
break;
case SECONDARY_GROUP_USER:
action = MappingRuleActions.createPlaceToQueueAction(
getTargetQueue(rule.getParentQueue(),
"%secondary_group.%user"), create);
break;
case SPECIFIED:
action = MappingRuleActions.createPlaceToQueueAction("%specified",
create);
break;
case CUSTOM:
String customTarget = rule.getCustomPlacement();
checkArgument(customTarget != null, "custom queue is undefined");
action = MappingRuleActions.createPlaceToQueueAction(customTarget,
create);
break;
case USER:
action = MappingRuleActions.createPlaceToQueueAction(
getTargetQueue(rule.getParentQueue(),
"%user"), create);
break;
case APPLICATION_NAME:
action = MappingRuleActions.createPlaceToQueueAction(
getTargetQueue(rule.getParentQueue(),
"%application"), create);
break;
case SET_DEFAULT_QUEUE:
String defaultQueue = rule.getValue();
checkArgument(defaultQueue != null, "default queue is undefined");
action = MappingRuleActions.createUpdateDefaultAction(defaultQueue);
break;
default:
throw new IllegalArgumentException(
"Unsupported policy: " + policy);
}
return action;
}
private void setFallbackToAction(Rule rule, MappingRuleAction action) {
FallbackResult fallbackResult = rule.getFallbackResult();
if (fallbackResult == null) {
action.setFallbackSkip();
LOG.debug("Fallback is not defined for rule {}, using SKIP as default", rule);
return;
}
switch (fallbackResult) {
case PLACE_DEFAULT:
action.setFallbackDefaultPlacement();
break;
case REJECT:
action.setFallbackReject();
break;
case SKIP:
action.setFallbackSkip();
break;
default:
throw new IllegalArgumentException(
"Unsupported fallback rule " + fallbackResult);
}
}
private String getTargetQueue(String parent, String placeholder) {
return (parent == null) ? placeholder : parent + "." + placeholder;
}
private void checkMandatoryParameters(Rule rule) {
checkArgument(rule.getPolicy() != null, "Rule policy is undefined");
checkArgument(rule.getType() != null, "Rule type is undefined");
checkArgument(rule.getMatches() != null, "Match string is undefined");
checkArgument(!StringUtils.isEmpty(rule.getMatches()),
"Match string is empty");
}
} | MappingRuleCreator |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/TestEntityQuery.java | {
"start": 781,
"end": 1279
} | class ____ extends DefaultEntityQuery {
/**
* Creates a new {@link DefaultEntityQuery} from the given JPQL query.
*
* @param query must not be {@literal null} or empty.
*/
TestEntityQuery(String query, boolean isNative) {
super(PreprocessedQuery.parse(isNative ? DeclaredQuery.nativeQuery(query) : DeclaredQuery.jpqlQuery(query)),
QueryEnhancerSelector.DEFAULT_SELECTOR
.select(isNative ? DeclaredQuery.nativeQuery(query) : DeclaredQuery.jpqlQuery(query)));
}
}
| TestEntityQuery |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/task/budget/Budget.java | {
"start": 941,
"end": 2428
} | interface ____ {
/**
* Defines an initial delay before running the task
*
* @return the initial delay, in milliseconds, before running the task
*/
long initialDelay();
/**
* The interval between each task execution (delay between the termination of one execution and the commencement of
* the next).
*
* @return the interval, in milliseconds, for each task execution
*/
long interval();
/**
* Whether the task has budget to continue executing or not
*
* @return true if the task can continue or false otherwise
*/
boolean canContinue();
/**
* Move the task to the next iteration
*
* @return true if the task can continue or false otherwise
*/
boolean next();
/**
* The current number of iterations
*
* @return the current number of iterations
*/
int iteration();
/**
* The amount of time that has elapsed since the budget was created. This can be used to account for the amount of
* time it took to run a task. The precision should be withing a few microseconds/milliseconds due to the start time
* being created along with the budget instance. We do so to avoid the overhead of checking it the next or
* canContinue methods because they could be part of the hot path for some components.
*
* @return The amount of time that has elapsed since the budget was created
*/
Duration elapsed();
}
| Budget |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/tofix/MapFormatShape5405Test.java | {
"start": 924,
"end": 1551
} | class ____
{
public Map5405AsPOJO a;
public Map5405Base b;
@JsonFormat(shape=JsonFormat.Shape.POJO)
public Map5405Base c;
public Bean5405Container(int forA, int forB, int forC) {
if (forA != 0) {
a = new Map5405AsPOJO();
a.put("value", forA);
}
if (forB != 0) {
b = new Map5405Base();
b.put("value", forB);
}
if (forC != 0) {
c = new Map5405Base();
c.put("value", forC);
}
}
}
static | Bean5405Container |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/env/SimpleCommandLinePropertySource.java | {
"start": 3647,
"end": 4971
} | class ____ extends CommandLinePropertySource<CommandLineArgs> {
/**
* Create a new {@code SimpleCommandLinePropertySource} having the default name
* and backed by the given {@code String[]} of command line arguments.
* @see CommandLinePropertySource#COMMAND_LINE_PROPERTY_SOURCE_NAME
* @see CommandLinePropertySource#CommandLinePropertySource(Object)
*/
public SimpleCommandLinePropertySource(String... args) {
super(new SimpleCommandLineArgsParser().parse(args));
}
/**
* Create a new {@code SimpleCommandLinePropertySource} having the given name
* and backed by the given {@code String[]} of command line arguments.
*/
public SimpleCommandLinePropertySource(String name, String[] args) {
super(name, new SimpleCommandLineArgsParser().parse(args));
}
/**
* Get the property names for the option arguments.
*/
@Override
public String[] getPropertyNames() {
return StringUtils.toStringArray(this.source.getOptionNames());
}
@Override
protected boolean containsOption(String name) {
return this.source.containsOption(name);
}
@Override
protected @Nullable List<String> getOptionValues(String name) {
return this.source.getOptionValues(name);
}
@Override
protected List<String> getNonOptionArgs() {
return this.source.getNonOptionArgs();
}
}
| SimpleCommandLinePropertySource |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/ml/JavaChiSqSelectorExample.java | {
"start": 1404,
"end": 2658
} | class ____ {
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("JavaChiSqSelectorExample")
.getOrCreate();
// $example on$
List<Row> data = Arrays.asList(
RowFactory.create(7, Vectors.dense(0.0, 0.0, 18.0, 1.0), 1.0),
RowFactory.create(8, Vectors.dense(0.0, 1.0, 12.0, 0.0), 0.0),
RowFactory.create(9, Vectors.dense(1.0, 0.0, 15.0, 0.1), 0.0)
);
StructType schema = new StructType(new StructField[]{
new StructField("id", DataTypes.IntegerType, false, Metadata.empty()),
new StructField("features", new VectorUDT(), false, Metadata.empty()),
new StructField("clicked", DataTypes.DoubleType, false, Metadata.empty())
});
Dataset<Row> df = spark.createDataFrame(data, schema);
ChiSqSelector selector = new ChiSqSelector()
.setNumTopFeatures(1)
.setFeaturesCol("features")
.setLabelCol("clicked")
.setOutputCol("selectedFeatures");
Dataset<Row> result = selector.fit(df).transform(df);
System.out.println("ChiSqSelector output with top " + selector.getNumTopFeatures()
+ " features selected");
result.show();
// $example off$
spark.stop();
}
}
| JavaChiSqSelectorExample |
java | micronaut-projects__micronaut-core | context/src/main/java/io/micronaut/scheduling/cron/CronExpression.java | {
"start": 12971,
"end": 19240
} | class ____ {
private static final Pattern CRON_FIELD_REGEXP = Pattern
.compile("""
(?: # start of group 1
(?:(?<all>\\*)|(?<ignore>\\?)|(?<last>L)) # global flag (L, ?, *)
| (?<start>[0-9]{1,2}|[a-z]{3,3}) # or start number or symbol
(?: # start of group 2
(?<mod>L|W) # modifier (L, W)
| -(?<end>[0-9]{1,2}|[a-z]{3,3}) # or end nummer or symbol (in range)
)? # end of group 2
) # end of group 1
(?:(?<incmod>/|\\#)(?<inc>[0-9]{1,7}))? # increment and increment modifier (/ or \\#)
""",
Pattern.CASE_INSENSITIVE | Pattern.COMMENTS);
private static final int PART_INCREMENT = 999;
final CronFieldType fieldType;
/**
* Represent parts for the cron field.
*/
final List<FieldPart> parts = new ArrayList<>();
private BasicField(CronFieldType fieldType, String fieldExpr) {
this.fieldType = fieldType;
parse(fieldExpr);
}
/**
* Create a {@link BasicField} from the given String expression.
*
* @param fieldExpr String expression for a field
*/
private void parse(String fieldExpr) { // NOSONAR
String[] rangeParts = fieldExpr.split(",");
for (String rangePart : rangeParts) {
Matcher m = CRON_FIELD_REGEXP.matcher(rangePart);
if (!m.matches()) {
throw new IllegalArgumentException("Invalid cron field '" + rangePart + "' for field [" + fieldType + "]");
}
String startNummer = m.group("start");
String modifier = m.group("mod");
String sluttNummer = m.group("end");
String incrementModifier = m.group("incmod");
String increment = m.group("inc");
FieldPart part = new FieldPart();
part.increment = PART_INCREMENT;
if (startNummer != null) {
part.from = mapValue(startNummer);
part.modifier = modifier;
if (sluttNummer != null) {
part.to = mapValue(sluttNummer);
part.increment = 1;
} else if (increment != null) {
part.to = fieldType.to;
} else {
part.to = part.from;
}
} else if (m.group("all") != null) {
part.from = fieldType.from;
part.to = fieldType.to;
part.increment = 1;
} else if (m.group("ignore") != null) {
part.modifier = m.group("ignore");
} else if (m.group("last") != null) {
part.modifier = m.group("last");
} else {
throw new IllegalArgumentException("Invalid cron part: " + rangePart);
}
if (increment != null) {
part.incrementModifier = incrementModifier;
part.increment = Integer.valueOf(increment);
}
validateRange(part);
validatePart(part);
parts.add(part);
}
}
/**
* Validate the cron field part.
*
* @param part The part of cron-field
*/
protected void validatePart(FieldPart part) {
if (part.modifier != null) {
throw new IllegalArgumentException("Invalid modifier [%s]".formatted(part.modifier));
} else if (part.incrementModifier != null && !"/".equals(part.incrementModifier)) {
throw new IllegalArgumentException("Invalid increment modifier [%s]".formatted(part.incrementModifier));
}
}
/**
* Validate range of the cron-field part.
*
* @param part The part of cron-field
*/
private void validateRange(FieldPart part) {
if ((part.from != null && part.from < fieldType.from) || (part.to != null && part.to > fieldType.to)) {
throw new IllegalArgumentException("Invalid interval [%s-%s], must be %s<=_<=%s".formatted(part.from, part.to, fieldType.from,
fieldType.to));
} else if (part.from != null && part.to != null && part.from > part.to) {
throw new IllegalArgumentException(
"Invalid interval [%s-%s]. Rolling periods are not supported (ex. 5-1, only 1-5) since this won't give a deterministic result. Must be %s<=_<=%s".formatted(
part.from, part.to, fieldType.from, fieldType.to));
}
}
/**
* Map value to the {@link CronFieldType} name.
*
* @param value The value to map to names of {@link CronFieldType}
* @return The integer value of name from the names for cron-field type
*/
protected Integer mapValue(String value) {
Integer idx;
if (fieldType.names != null) {
idx = fieldType.names.indexOf(value.toUpperCase(Locale.getDefault()));
if (idx >= 0) {
return idx + 1;
}
}
return Integer.valueOf(value);
}
/**
* @param val The value
* @param part Cron field part to match to
* @return True/False if the value matches the field part
*/
protected boolean matches(int val, FieldPart part) {
return val >= part.from && val <= part.to && (val - part.from) % part.increment == 0;
}
}
/**
* A | BasicField |
java | apache__flink | flink-streaming-java/src/test/java/org/apache/flink/streaming/api/functions/sink/filesystem/TestUtils.java | {
"start": 12838,
"end": 13334
} | class ____
implements BucketAssigner<Tuple2<String, Integer>, Integer> {
private static final long serialVersionUID = 1L;
@Override
public Integer getBucketId(Tuple2<String, Integer> element, Context context) {
return element.f1;
}
@Override
public SimpleVersionedSerializer<Integer> getSerializer() {
return new SimpleVersionedIntegerSerializer();
}
}
private static final | TupleToIntegerBucketer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ReferenceEqualityTest.java | {
"start": 10536,
"end": 10839
} | class ____ {
public void f(Missing m) {}
public void g(Missing m) {}
}
@Test
public void erroneous() {
compilationHelper
.addSourceLines(
"Test.java",
"import " + MayImplementEquals.class.getCanonicalName() + ";",
"abstract | MayImplementEquals |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/masterslave/StatefulRedisMasterSlaveConnection.java | {
"start": 538,
"end": 1167
} | interface ____<K, V> extends StatefulRedisMasterReplicaConnection<K, V> {
/**
* Set from which nodes data is read. The setting is used as default for read operations on this connection. See the
* documentation for {@link ReadFrom} for more information.
*
* @param readFrom the read from setting, must not be {@code null}
*/
void setReadFrom(ReadFrom readFrom);
/**
* Gets the {@link ReadFrom} setting for this connection. Defaults to {@link ReadFrom#UPSTREAM} if not set.
*
* @return the read from setting
*/
ReadFrom getReadFrom();
}
| StatefulRedisMasterSlaveConnection |
java | elastic__elasticsearch | x-pack/plugin/ml-package-loader/src/test/java/org/elasticsearch/xpack/ml/packageloader/action/ModelImporterTests.java | {
"start": 2075,
"end": 15480
} | class ____ extends ESTestCase {
private TestThreadPool threadPool;
@Before
public void createThreadPool() {
threadPool = createThreadPool(MachineLearningPackageLoader.modelDownloadExecutor(Settings.EMPTY));
}
@After
public void closeThreadPool() {
threadPool.close();
}
public void testDownloadModelDefinition() throws InterruptedException, URISyntaxException {
var client = mockClient(false);
var task = ModelDownloadTaskTests.testTask();
var config = mockConfigWithRepoLinks();
var vocab = new ModelLoaderUtils.VocabularyParts(List.of(), List.of(), List.of());
var cbs = mock(CircuitBreakerService.class);
when(cbs.getBreaker(eq(CircuitBreaker.REQUEST))).thenReturn(mock(CircuitBreaker.class));
int totalParts = 5;
int chunkSize = 10;
long size = totalParts * chunkSize;
var modelDef = modelDefinition(totalParts, chunkSize);
var streamers = mockHttpStreamChunkers(modelDef, chunkSize, 2);
var digest = computeDigest(modelDef);
when(config.getSha256()).thenReturn(digest);
when(config.getSize()).thenReturn(size);
var importer = new ModelImporter(client, "foo", config, task, threadPool, cbs);
var latch = new CountDownLatch(1);
var latchedListener = new LatchedActionListener<AcknowledgedResponse>(ActionTestUtils.assertNoFailureListener(ignore -> {}), latch);
importer.downloadModelDefinition(size, totalParts, vocab, streamers, latchedListener);
latch.await();
verify(client, times(totalParts)).execute(eq(PutTrainedModelDefinitionPartAction.INSTANCE), any());
assertEquals(totalParts - 1, task.getStatus().downloadProgress().downloadedParts());
assertEquals(totalParts, task.getStatus().downloadProgress().totalParts());
}
public void testReadModelDefinitionFromFile() throws InterruptedException, URISyntaxException {
var client = mockClient(false);
var task = ModelDownloadTaskTests.testTask();
var config = mockConfigWithRepoLinks();
var vocab = new ModelLoaderUtils.VocabularyParts(List.of(), List.of(), List.of());
var cbs = mock(CircuitBreakerService.class);
when(cbs.getBreaker(eq(CircuitBreaker.REQUEST))).thenReturn(mock(CircuitBreaker.class));
int totalParts = 3;
int chunkSize = 10;
long size = totalParts * chunkSize;
var modelDef = modelDefinition(totalParts, chunkSize);
var digest = computeDigest(modelDef);
when(config.getSha256()).thenReturn(digest);
when(config.getSize()).thenReturn(size);
var importer = new ModelImporter(client, "foo", config, task, threadPool, cbs);
var streamChunker = new ModelLoaderUtils.InputStreamChunker(new ByteArrayInputStream(modelDef), chunkSize);
var latch = new CountDownLatch(1);
var latchedListener = new LatchedActionListener<AcknowledgedResponse>(ActionTestUtils.assertNoFailureListener(ignore -> {}), latch);
importer.readModelDefinitionFromFile(size, totalParts, streamChunker, vocab, latchedListener);
latch.await();
verify(client, times(totalParts)).execute(eq(PutTrainedModelDefinitionPartAction.INSTANCE), any());
assertEquals(totalParts, task.getStatus().downloadProgress().downloadedParts());
assertEquals(totalParts, task.getStatus().downloadProgress().totalParts());
}
public void testSizeMismatch() throws InterruptedException, URISyntaxException {
var client = mockClient(false);
var task = mock(ModelDownloadTask.class);
var config = mockConfigWithRepoLinks();
var cbs = mock(CircuitBreakerService.class);
when(cbs.getBreaker(eq(CircuitBreaker.REQUEST))).thenReturn(mock(CircuitBreaker.class));
int totalParts = 5;
int chunkSize = 10;
long size = totalParts * chunkSize;
var modelDef = modelDefinition(totalParts, chunkSize);
var streamers = mockHttpStreamChunkers(modelDef, chunkSize, 2);
var digest = computeDigest(modelDef);
when(config.getSha256()).thenReturn(digest);
when(config.getSize()).thenReturn(size - 1); // expected size and read size are different
var exceptionHolder = new AtomicReference<Exception>();
var latch = new CountDownLatch(1);
var latchedListener = new LatchedActionListener<AcknowledgedResponse>(
ActionTestUtils.assertNoSuccessListener(exceptionHolder::set),
latch
);
var importer = new ModelImporter(client, "foo", config, task, threadPool, cbs);
importer.downloadModelDefinition(size, totalParts, null, streamers, latchedListener);
latch.await();
assertThat(exceptionHolder.get().getMessage(), containsString("Model size does not match"));
verify(client, times(totalParts)).execute(eq(PutTrainedModelDefinitionPartAction.INSTANCE), any());
}
public void testDigestMismatch() throws InterruptedException, URISyntaxException {
var client = mockClient(false);
var task = mock(ModelDownloadTask.class);
var config = mockConfigWithRepoLinks();
var cbs = mock(CircuitBreakerService.class);
when(cbs.getBreaker(eq(CircuitBreaker.REQUEST))).thenReturn(mock(CircuitBreaker.class));
int totalParts = 5;
int chunkSize = 10;
long size = totalParts * chunkSize;
var modelDef = modelDefinition(totalParts, chunkSize);
var streamers = mockHttpStreamChunkers(modelDef, chunkSize, 2);
when(config.getSha256()).thenReturn("0x"); // digest is different
when(config.getSize()).thenReturn(size);
var exceptionHolder = new AtomicReference<Exception>();
var latch = new CountDownLatch(1);
var latchedListener = new LatchedActionListener<AcknowledgedResponse>(
ActionTestUtils.assertNoSuccessListener(exceptionHolder::set),
latch
);
var importer = new ModelImporter(client, "foo", config, task, threadPool, cbs);
// Message digest can only be calculated for the file reader
var streamChunker = new ModelLoaderUtils.InputStreamChunker(new ByteArrayInputStream(modelDef), chunkSize);
importer.readModelDefinitionFromFile(size, totalParts, streamChunker, null, latchedListener);
latch.await();
assertThat(exceptionHolder.get().getMessage(), containsString("Model sha256 checksums do not match"));
verify(client, times(totalParts)).execute(eq(PutTrainedModelDefinitionPartAction.INSTANCE), any());
}
public void testPutFailure() throws InterruptedException, URISyntaxException {
var client = mockClient(true); // client will fail put
var task = mock(ModelDownloadTask.class);
var config = mockConfigWithRepoLinks();
var cbs = mock(CircuitBreakerService.class);
when(cbs.getBreaker(eq(CircuitBreaker.REQUEST))).thenReturn(mock(CircuitBreaker.class));
int totalParts = 4;
int chunkSize = 10;
long size = totalParts * chunkSize;
var modelDef = modelDefinition(totalParts, chunkSize);
var streamers = mockHttpStreamChunkers(modelDef, chunkSize, 1);
var exceptionHolder = new AtomicReference<Exception>();
var latch = new CountDownLatch(1);
var latchedListener = new LatchedActionListener<AcknowledgedResponse>(
ActionTestUtils.assertNoSuccessListener(exceptionHolder::set),
latch
);
var importer = new ModelImporter(client, "foo", config, task, threadPool, cbs);
importer.downloadModelDefinition(size, totalParts, null, streamers, latchedListener);
latch.await();
assertThat(exceptionHolder.get().getMessage(), containsString("put model part failed"));
verify(client, times(1)).execute(eq(PutTrainedModelDefinitionPartAction.INSTANCE), any());
}
public void testReadFailure() throws IOException, InterruptedException, URISyntaxException {
var client = mockClient(true);
var task = mock(ModelDownloadTask.class);
var config = mockConfigWithRepoLinks();
var cbs = mock(CircuitBreakerService.class);
when(cbs.getBreaker(eq(CircuitBreaker.REQUEST))).thenReturn(mock(CircuitBreaker.class));
int totalParts = 4;
int chunkSize = 10;
long size = totalParts * chunkSize;
var streamer = mock(ModelLoaderUtils.HttpStreamChunker.class);
when(streamer.hasNext()).thenReturn(true);
when(streamer.next()).thenThrow(new IOException("stream failed")); // fail the read
var exceptionHolder = new AtomicReference<Exception>();
var latch = new CountDownLatch(1);
var latchedListener = new LatchedActionListener<AcknowledgedResponse>(
ActionTestUtils.assertNoSuccessListener(exceptionHolder::set),
latch
);
var importer = new ModelImporter(client, "foo", config, task, threadPool, cbs);
importer.downloadModelDefinition(size, totalParts, null, List.of(streamer), latchedListener);
latch.await();
assertThat(exceptionHolder.get().getMessage(), containsString("stream failed"));
}
@SuppressWarnings("unchecked")
public void testUploadVocabFailure() throws InterruptedException, URISyntaxException {
var client = mock(Client.class);
doAnswer(invocation -> {
ActionListener<AcknowledgedResponse> listener = (ActionListener<AcknowledgedResponse>) invocation.getArguments()[2];
listener.onFailure(new ElasticsearchStatusException("put vocab failed", RestStatus.BAD_REQUEST));
return null;
}).when(client).execute(eq(PutTrainedModelVocabularyAction.INSTANCE), any(), any());
var cbs = mock(CircuitBreakerService.class);
when(cbs.getBreaker(eq(CircuitBreaker.REQUEST))).thenReturn(mock(CircuitBreaker.class));
var task = mock(ModelDownloadTask.class);
var config = mockConfigWithRepoLinks();
var vocab = new ModelLoaderUtils.VocabularyParts(List.of(), List.of(), List.of());
var exceptionHolder = new AtomicReference<Exception>();
var latch = new CountDownLatch(1);
var latchedListener = new LatchedActionListener<AcknowledgedResponse>(
ActionTestUtils.assertNoSuccessListener(exceptionHolder::set),
latch
);
var importer = new ModelImporter(client, "foo", config, task, threadPool, cbs);
importer.downloadModelDefinition(100, 5, vocab, List.of(), latchedListener);
latch.await();
assertThat(exceptionHolder.get().getMessage(), containsString("put vocab failed"));
verify(client, times(1)).execute(eq(PutTrainedModelVocabularyAction.INSTANCE), any(), any());
verify(client, never()).execute(eq(PutTrainedModelDefinitionPartAction.INSTANCE), any());
}
private List<ModelLoaderUtils.HttpStreamChunker> mockHttpStreamChunkers(byte[] modelDef, int chunkSize, int numStreams) {
var ranges = ModelLoaderUtils.split(modelDef.length, numStreams, chunkSize);
var result = new ArrayList<ModelLoaderUtils.HttpStreamChunker>(ranges.size());
for (var range : ranges) {
int len = range.numParts() * chunkSize;
var modelDefStream = new ByteArrayInputStream(modelDef, (int) range.rangeStart(), len);
result.add(new ModelLoaderUtils.HttpStreamChunker(modelDefStream, range, chunkSize));
}
return result;
}
private byte[] modelDefinition(int totalParts, int chunkSize) {
var bytes = new byte[totalParts * chunkSize];
for (int i = 0; i < totalParts; i++) {
System.arraycopy(randomByteArrayOfLength(chunkSize), 0, bytes, i * chunkSize, chunkSize);
}
return bytes;
}
private String computeDigest(byte[] modelDef) {
var digest = MessageDigests.sha256();
digest.update(modelDef);
return MessageDigests.toHexString(digest.digest());
}
@SuppressWarnings("unchecked")
private Client mockClient(boolean failPutPart) {
var client = mock(Client.class);
if (failPutPart) {
when(client.execute(eq(PutTrainedModelDefinitionPartAction.INSTANCE), any())).thenThrow(
new IllegalStateException("put model part failed")
);
} else {
ActionFuture<AcknowledgedResponse> future = mock(ActionFuture.class);
when(future.actionGet()).thenReturn(AcknowledgedResponse.TRUE);
when(client.execute(eq(PutTrainedModelDefinitionPartAction.INSTANCE), any())).thenReturn(future);
}
doAnswer(invocation -> {
ActionListener<AcknowledgedResponse> listener = (ActionListener<AcknowledgedResponse>) invocation.getArguments()[2];
listener.onResponse(AcknowledgedResponse.TRUE);
return null;
}).when(client).execute(eq(PutTrainedModelVocabularyAction.INSTANCE), any(), any());
return client;
}
private ModelPackageConfig mockConfigWithRepoLinks() {
var config = mock(ModelPackageConfig.class);
when(config.getModelRepository()).thenReturn("https://models.models");
when(config.getPackagedModelId()).thenReturn("my-model");
return config;
}
}
| ModelImporterTests |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/job/checkpoints/AbstractCheckpointHandler.java | {
"start": 2181,
"end": 5104
} | class ____<
R extends ResponseBody, M extends CheckpointMessageParameters>
extends AbstractCheckpointStatsHandler<R, M> {
private final CheckpointStatsCache checkpointStatsCache;
protected AbstractCheckpointHandler(
GatewayRetriever<? extends RestfulGateway> leaderRetriever,
Duration timeout,
Map<String, String> responseHeaders,
MessageHeaders<EmptyRequestBody, R, M> messageHeaders,
Executor executor,
Cache<JobID, CompletableFuture<CheckpointStatsSnapshot>> checkpointStatsSnapshotCache,
CheckpointStatsCache checkpointStatsCache) {
super(
leaderRetriever,
timeout,
responseHeaders,
messageHeaders,
checkpointStatsSnapshotCache,
executor);
this.checkpointStatsCache = Preconditions.checkNotNull(checkpointStatsCache);
}
@Override
protected R handleCheckpointStatsRequest(
HandlerRequest<EmptyRequestBody> request,
CheckpointStatsSnapshot checkpointStatsSnapshot)
throws RestHandlerException {
JobID jobId = request.getPathParameter(JobIDPathParameter.class);
final long checkpointId = request.getPathParameter(CheckpointIdPathParameter.class);
if (checkpointStatsSnapshot != null) {
AbstractCheckpointStats checkpointStats =
checkpointStatsSnapshot.getHistory().getCheckpointById(checkpointId);
if (checkpointStats != null) {
checkpointStatsCache.tryAdd(checkpointStats);
} else {
checkpointStats = checkpointStatsCache.tryGet(checkpointId);
}
if (checkpointStats != null) {
return handleCheckpointRequest(request, checkpointStats);
} else {
throw new RestHandlerException(
"Could not find checkpointing statistics for checkpoint "
+ checkpointId
+ '.',
HttpResponseStatus.NOT_FOUND);
}
} else {
throw new RestHandlerException(
"Checkpointing was not enabled for job " + jobId + '.',
HttpResponseStatus.NOT_FOUND);
}
}
/**
* Called for each request with the corresponding {@link AbstractCheckpointStats} instance.
*
* @param request for further information
* @param checkpointStats for which the handler is called
* @return Response
* @throws RestHandlerException if the handler could not handle the request
*/
protected abstract R handleCheckpointRequest(
HandlerRequest<EmptyRequestBody> request, AbstractCheckpointStats checkpointStats)
throws RestHandlerException;
}
| AbstractCheckpointHandler |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TempDirectoryTests.java | {
"start": 13163,
"end": 16214
} | class ____ {
@Test
@DisplayName("when @TempDir is used on static field of an unsupported type")
@Order(20)
void onlySupportsStaticFieldsOfTypePathAndFile() {
var results = executeTestsForClass(AnnotationOnStaticFieldWithUnsupportedTypeTestCase.class);
assertSingleFailedContainer(results, ExtensionConfigurationException.class,
"Can only resolve @TempDir field of type java.nio.file.Path or java.io.File");
}
@Test
@DisplayName("when @TempDir is used on instance field of an unsupported type")
@Order(21)
void onlySupportsInstanceFieldsOfTypePathAndFile() {
var results = executeTestsForClass(AnnotationOnInstanceFieldWithUnsupportedTypeTestCase.class);
assertSingleFailedTest(results, ExtensionConfigurationException.class,
"Can only resolve @TempDir field of type java.nio.file.Path or java.io.File");
}
@Test
@DisplayName("when @TempDir is used on parameter of an unsupported type")
@Order(22)
void onlySupportsParametersOfTypePathAndFile() {
var results = executeTestsForClass(InvalidTestCase.class);
// @formatter:off
assertSingleFailedTest(results, instanceOf(ParameterResolutionException.class),
message(m -> m.matches("Failed to resolve parameter \\[java.lang.String .+] in method \\[.+]: .+")),
cause(
instanceOf(ExtensionConfigurationException.class),
message("Can only resolve @TempDir parameter of type java.nio.file.Path or java.io.File but was: java.lang.String")));
// @formatter:on
}
@Test
@DisplayName("when @TempDir factory does not return directory")
@Order(32)
void doesNotSupportTempDirFactoryNotReturningDirectory() {
var results = executeTestsForClass(FactoryNotReturningDirectoryTestCase.class);
// @formatter:off
assertSingleFailedTest(results, instanceOf(ParameterResolutionException.class),
message(m -> m.matches("Failed to resolve parameter \\[.+] in method \\[.+]: .+")),
cause(
instanceOf(ExtensionConfigurationException.class),
message("Failed to create default temp directory"),
cause(
instanceOf(PreconditionViolationException.class),
message("temp directory must be a directory")
)
));
// @formatter:on
}
@Test
@DisplayName("when default @TempDir factory does not return directory")
@Order(33)
void doesNotSupportCustomDefaultTempDirFactoryNotReturningDirectory() {
var results = executeTestsForClassWithDefaultFactory(
CustomDefaultFactoryNotReturningDirectoryTestCase.class, FactoryNotReturningDirectory.class);
// @formatter:off
assertSingleFailedTest(results, instanceOf(ParameterResolutionException.class),
message(m -> m.matches("Failed to resolve parameter \\[.+] in method \\[.+]: .+")),
cause(
instanceOf(ExtensionConfigurationException.class),
message("Failed to create default temp directory"),
cause(
instanceOf(PreconditionViolationException.class),
message("temp directory must be a directory")
)
));
// @formatter:on
}
private static | Failures |
java | quarkusio__quarkus | independent-projects/qute/core/src/test/java/io/quarkus/qute/NamespaceResolversTest.java | {
"start": 332,
"end": 3270
} | class ____ {
@Test
public void testMultipleSamePriority() {
assertThatIllegalArgumentException()
.isThrownBy(() -> Engine.builder()
.addNamespaceResolver(NamespaceResolver.builder("foo").resolve(e -> null).build())
.addNamespaceResolver(NamespaceResolver.builder("foo").resolve(e -> null).build()))
.withMessageStartingWith("Namespace [foo] may not be handled by multiple resolvers of the same priority [1]:");
}
@Test
public void testMultipleDifferentPriority() {
Engine engine = Engine.builder().addNamespaceResolver(NamespaceResolver.builder("foo").resolve(e -> {
return "foo1";
}).build()).addNamespaceResolver(NamespaceResolver.builder("foo").priority(50).resolve(e -> {
return "foo2";
}).build()).build();
assertEquals("foo2", engine.parse("{foo:baz}").render());
}
@Test
public void testMultipleAndNotFound() {
Engine engine = Engine.builder().addValueResolver(new ReflectionValueResolver())
.addNamespaceResolver(NamespaceResolver.builder("foo").resolve(e -> "foo1").build())
// This one should we used first but returns NOT_FOUND and so the other resolver is used
.addNamespaceResolver(NamespaceResolver.builder("foo").priority(50).resolve(Results.NotFound::from).build())
.build();
assertEquals("FOO1", engine.parse("{foo:baz.toUpperCase}").render());
}
@Test
public void testInvalidNamespace() {
assertThatExceptionOfType(TemplateException.class)
.isThrownBy(() -> Engine.builder()
.addNamespaceResolver(NamespaceResolver.builder("foo:").resolve(ec -> "foo").build()))
.withMessageContaining("[foo:] is not a valid namespace");
assertThatExceptionOfType(TemplateException.class)
.isThrownBy(() -> Engine.builder().addNamespaceResolver(new NamespaceResolver() {
@Override
public CompletionStage<Object> resolve(EvalContext context) {
return null;
}
@Override
public String getNamespace() {
return "$#%$%#$%";
}
}))
.withMessageContaining("[$#%$%#$%] is not a valid namespace");
}
@Test
public void testNoNamespaceFound() {
assertThatExceptionOfType(TemplateException.class)
.isThrownBy(() -> Engine.builder().addDefaults().build().parse("{charlie:name}", null, "alpha.html").render())
.withMessage(
"Rendering error in template [alpha.html:1]: No namespace resolver found for [charlie] in expression {charlie:name}")
.hasFieldOrProperty("code");
}
}
| NamespaceResolversTest |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/configuration/RecursiveComparisonConfiguration_shouldIgnoreFields_Test.java | {
"start": 1884,
"end": 17128
} | class ____ {
private RecursiveComparisonConfiguration recursiveComparisonConfiguration;
@BeforeEach
void setup() {
recursiveComparisonConfiguration = new RecursiveComparisonConfiguration();
}
@ParameterizedTest(name = "{0} should be ignored")
@MethodSource
void should_ignore_actual_null_fields(DualValue dualValue) {
// GIVEN
recursiveComparisonConfiguration.setIgnoreAllActualNullFields(true);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).as("%s should be ignored", dualValue).isTrue();
}
private static Stream<Arguments> should_ignore_actual_null_fields() {
return Stream.of(arguments(dualValue(null, "John")),
arguments(dualValue(null, 123)),
arguments(dualValue(null, null)),
arguments(dualValue(null, new Date())));
}
@ParameterizedTest(name = "{0} should be ignored")
@MethodSource
void should_ignore_actual_optional_empty_fields(DualValue dualValue) {
// GIVEN
recursiveComparisonConfiguration.setIgnoreAllActualEmptyOptionalFields(true);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).as("%s should be ignored", dualValue).isTrue();
}
private static Stream<Arguments> should_ignore_actual_optional_empty_fields() {
return Stream.of(arguments(dualValue(Optional.empty(), "John")),
arguments(dualValue(Optional.empty(), Optional.of("John"))),
arguments(dualValue(OptionalInt.empty(), OptionalInt.of(123))),
arguments(dualValue(OptionalLong.empty(), OptionalLong.of(123L))),
arguments(dualValue(OptionalDouble.empty(), OptionalDouble.of(123.0))));
}
@ParameterizedTest(name = "{0} should be ignored")
@MethodSource
void should_ignore_expected_null_fields(DualValue dualValue) {
// GIVEN
recursiveComparisonConfiguration.setIgnoreAllExpectedNullFields(true);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).as("%s should be ignored", dualValue).isTrue();
}
private static Stream<Arguments> should_ignore_expected_null_fields() {
return Stream.of(arguments(dualValue("John", null)),
arguments(dualValue(123, null)),
arguments(dualValue(null, null)),
arguments(dualValue(new Date(), null)));
}
@ParameterizedTest(name = "{0} should be ignored with these ignored fields {1}")
@MethodSource
void should_ignore_specified_fields(DualValue dualValue, List<String> ignoredFields) {
// GIVEN
recursiveComparisonConfiguration.ignoreFields(ignoredFields.toArray(new String[0]));
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).as("%s should be ignored with these ignored fields %s", dualValue, ignoredFields).isTrue();
}
private static Stream<Arguments> should_ignore_specified_fields() {
return Stream.of(arguments(dualValueWithPath("name"), list("name")),
arguments(dualValueWithPath("name", "first"), list("name")),
arguments(dualValueWithPath("name", "first", "nickname"), list("name")),
arguments(dualValueWithPath("name", "first", "nickname"), list("name.first")),
arguments(dualValueWithPath("name"), list("foo", "name", "foo")),
arguments(dualValueWithPath("name", "first"), list("name.first")),
arguments(dualValueWithPath("name", "[2]", "first"), list("name.first")),
arguments(dualValueWithPath("[0]", "first"), list("first")),
arguments(dualValueWithPath("[1]", "first", "second"), list("first.second")),
arguments(dualValueWithPath("father", "name", "first"), list("father", "name.first", "father.name.first")));
}
@ParameterizedTest(name = "{0} should not be ignored with these ignored fields {1}")
@MethodSource
void should_not_ignore_specified_fields(DualValue dualValue, List<String> ignoredFields) {
// GIVEN
recursiveComparisonConfiguration.ignoreFields(ignoredFields.toArray(new String[0]));
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).as("%s should not be ignored with these ignored fields %s", dualValue, ignoredFields).isFalse();
}
private static Stream<Arguments> should_not_ignore_specified_fields() {
return Stream.of(arguments(dualValueWithPath("names"), list("name")),
arguments(dualValueWithPath("nickname"), list("name")),
arguments(dualValueWithPath("name"), list("nickname")),
arguments(dualValueWithPath("name"), list("name.first")),
arguments(dualValueWithPath("person", "name"), list("name")),
arguments(dualValueWithPath("first", "nickname"), list("name")));
}
@ParameterizedTest(name = "{0} should be ignored with these regexes {1}")
@MethodSource
void should_ignore_fields_matching_given_regexes(DualValue dualValue, List<String> regexes) {
// GIVEN
recursiveComparisonConfiguration.ignoreFieldsMatchingRegexes(regexes.toArray(new String[0]));
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).as("%s should be ignored with these regexes %s", dualValue, regexes).isTrue();
}
private static Stream<Arguments> should_ignore_fields_matching_given_regexes() {
return Stream.of(arguments(dualValueWithPath("name"), list(".*name")),
arguments(dualValueWithPath("name"), list("foo", "n.m.", "foo")),
arguments(dualValueWithPath("name", "first"), list("name")),
arguments(dualValueWithPath("name", "first"), list("name\\.first")),
arguments(dualValueWithPath("name", "first"), list(".*first")),
arguments(dualValueWithPath("name", "first"), list("name.*")),
arguments(dualValueWithPath("name", "[2]", "first"), list("name\\.first")),
arguments(dualValueWithPath("[0]", "first"), list("fir.*")),
arguments(dualValueWithPath("[1]", "first", "second"), list("f..st\\..*nd")),
arguments(dualValueWithPath("father", "name", "first"),
list("father", "name.first", "father\\.name\\.first")));
}
@ParameterizedTest(name = "{0} should be ignored")
@MethodSource
void should_ignore_fields(DualValue dualValue) {
// GIVEN
recursiveComparisonConfiguration.ignoreFieldsMatchingRegexes(".*name");
recursiveComparisonConfiguration.ignoreFields("number");
recursiveComparisonConfiguration.ignoreFieldsOfTypes(String.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).as("%s should be ignored", dualValue).isTrue();
}
private static Stream<Arguments> should_ignore_fields() {
return Stream.of(arguments(dualValueWithPath("name")),
arguments(dualValueWithPath("number")),
arguments(dualValueWithPath("surname")),
arguments(dualValueWithPath("first", "name")),
arguments(new DualValue(randomPath(), "actual", "expected")));
}
@Test
void ignoring_fields_for_types_does_not_replace_previous_ignored_types() {
// WHEN
recursiveComparisonConfiguration.ignoreFieldsOfTypes(UUID.class);
recursiveComparisonConfiguration.ignoreFieldsOfTypes(ZonedDateTime.class, String.class);
// THEN
then(recursiveComparisonConfiguration.getIgnoredTypes()).containsExactlyInAnyOrder(UUID.class, ZonedDateTime.class,
String.class);
}
@ParameterizedTest(name = "{0} should be ignored with these ignored types {1}")
@MethodSource
void should_ignore_fields_for_specified_types(DualValue dualValue, List<Class<?>> ignoredTypes) {
// GIVEN
recursiveComparisonConfiguration.ignoreFieldsOfTypes(ignoredTypes.toArray(new Class<?>[0]));
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).as("%s should be ignored with these ignored types %s", dualValue, ignoredTypes)
.isTrue();
}
private static Stream<Arguments> should_ignore_fields_for_specified_types() {
return Stream.of(arguments(new DualValue(randomPath(), "actual", "expected"), list(String.class)),
arguments(new DualValue(randomPath(), randomUUID(), randomUUID()), list(String.class, UUID.class)));
}
@Test
void should_return_false_if_the_field_type_is_not_ignored() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), "actual", "expected");
recursiveComparisonConfiguration.ignoreFieldsOfTypes(UUID.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isFalse();
}
@Test
void should_be_able_to_ignore_boolean() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), true, false);
recursiveComparisonConfiguration.ignoreFieldsOfTypes(boolean.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isTrue();
}
@Test
void should_be_able_to_ignore_byte() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), (byte) 0, (byte) 1);
recursiveComparisonConfiguration.ignoreFieldsOfTypes(byte.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isTrue();
}
@Test
void should_be_able_to_ignore_char() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), 'a', 'b');
recursiveComparisonConfiguration.ignoreFieldsOfTypes(char.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isTrue();
}
@Test
void should_be_able_to_ignore_short() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), (short) 123, (short) 123);
recursiveComparisonConfiguration.ignoreFieldsOfTypes(short.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isTrue();
}
@Test
void should_be_able_to_ignore_int() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), 123, 123);
recursiveComparisonConfiguration.ignoreFieldsOfTypes(int.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isTrue();
}
@ParameterizedTest(name = "{2}: actual={0} / expected={1} / ignored types={3}")
@MethodSource
void should_be_able_to_ignore_concurrent_types_by_regex(Object value) {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), value, null);
recursiveComparisonConfiguration.ignoreFieldsOfTypesMatchingRegexes("java\\.util\\.concurrent\\..*");
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isTrue();
}
private static Stream<Object> should_be_able_to_ignore_concurrent_types_by_regex() {
return Stream.of(new ReentrantReadWriteLock(), new ReentrantLock(), completedFuture("done"));
}
@Test
void should_be_able_to_ignore_float() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), 123.0f, 123.0f);
recursiveComparisonConfiguration.ignoreFieldsOfTypes(float.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isTrue();
}
@Test
void should_be_able_to_ignore_double() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), 123.0, 123.0);
recursiveComparisonConfiguration.ignoreFieldsOfTypes(double.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isTrue();
}
@ParameterizedTest(name = "{0} should be ignored by specifying to ignore {1}")
@MethodSource
void should_be_able_to_ignore_primitive_field_by_specifying_their_wrapper_type(Object fieldValue, Class<?> wrapperType) {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), fieldValue, fieldValue);
recursiveComparisonConfiguration.ignoreFieldsOfTypes(wrapperType);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isTrue();
}
private static Stream<Arguments> should_be_able_to_ignore_primitive_field_by_specifying_their_wrapper_type() {
return Stream.of(arguments(false, Boolean.class),
arguments((byte) 0, Byte.class),
arguments('b', Character.class),
arguments(123, Integer.class),
arguments(123.0f, Float.class),
arguments(123.0, Double.class),
arguments((short) 123, Short.class));
}
@Test
void should_return_false_if_the_field_type_is_subtype_of_an_ignored_type() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), Double.MAX_VALUE, "expected");
recursiveComparisonConfiguration.ignoreFieldsOfTypes(Number.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isFalse();
}
@Test
void should_not_ignore_actual_null_fields_for_specified_types_if_strictTypeChecking_is_disabled() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), null, "expected");
recursiveComparisonConfiguration.strictTypeChecking(false);
recursiveComparisonConfiguration.ignoreFieldsOfTypes(String.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isFalse();
}
@Test
void should_ignore_actual_null_fields_for_specified_types_if_strictTypeChecking_is_enabled_and_expected_is_not_null() {
// GIVEN
DualValue dualValue = new DualValue(randomPath(), null, "expected");
recursiveComparisonConfiguration.strictTypeChecking(true);
recursiveComparisonConfiguration.ignoreFieldsOfTypes(String.class);
// WHEN
boolean ignored = recursiveComparisonConfiguration.shouldIgnore(dualValue);
// THEN
then(ignored).isTrue();
}
@Test
void should_treat_empty_compared_fields_as_not_restricting_comparison() {
// GIVEN
recursiveComparisonConfiguration.compareOnlyFields();
// WHEN
boolean shouldBeCompared = !recursiveComparisonConfiguration.shouldIgnore(dualValueWithPath("name"));
// THEN
then(shouldBeCompared).isTrue();
}
static DualValue dualValue(Object value1, Object value2) {
return new DualValue(randomPath(), value1, value2);
}
}
| RecursiveComparisonConfiguration_shouldIgnoreFields_Test |
java | micronaut-projects__micronaut-core | http-server-netty/src/test/groovy/io/micronaut/docs/http/server/exception/aterrorexceptionhandlerprecedence/OutOfStockController.java | {
"start": 1021,
"end": 1224
} | class ____ {
@Error(exception = OutOfStockException.class, global = true)
public HttpResponse handleOutOfStock(HttpRequest request) {
return HttpResponse.ok(-1);
}
}
| OutOfStockController |
java | elastic__elasticsearch | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/utils/time/DateTimeFormatterTimestampConverterTests.java | {
"start": 704,
"end": 5304
} | class ____ extends ESTestCase {
public void testOfPattern_GivenPatternIsOnlyYear() {
ESTestCase.expectThrows(IllegalArgumentException.class, () -> DateTimeFormatterTimestampConverter.ofPattern("y", ZoneOffset.UTC));
}
public void testOfPattern_GivenPatternIsOnlyDate() {
ESTestCase.expectThrows(
IllegalArgumentException.class,
() -> DateTimeFormatterTimestampConverter.ofPattern("y-M-d", ZoneOffset.UTC)
);
}
public void testOfPattern_GivenPatternIsOnlyTime() {
ESTestCase.expectThrows(
IllegalArgumentException.class,
() -> DateTimeFormatterTimestampConverter.ofPattern("HH:mm:ss", ZoneOffset.UTC)
);
}
public void testOfPattern_GivenPatternIsUsingYearInsteadOfYearOfEra() {
ESTestCase.expectThrows(
IllegalArgumentException.class,
() -> DateTimeFormatterTimestampConverter.ofPattern("uuuu-MM-dd HH:mm:ss", ZoneOffset.UTC)
);
}
public void testToEpochSeconds_GivenValidTimestampDoesNotFollowPattern() {
TimestampConverter formatter = DateTimeFormatterTimestampConverter.ofPattern("yyyy-MM-dd HH:mm:ss", ZoneOffset.UTC);
ESTestCase.expectThrows(DateTimeParseException.class, () -> formatter.toEpochSeconds("14:00:22"));
}
public void testToEpochMillis_GivenValidTimestampDoesNotFollowPattern() {
TimestampConverter formatter = DateTimeFormatterTimestampConverter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", ZoneOffset.UTC);
ESTestCase.expectThrows(DateTimeParseException.class, () -> formatter.toEpochMillis("2015-01-01 14:00:22"));
}
public void testToEpochSeconds_GivenPatternHasFullDateAndOnlyHours() {
long expected = ZonedDateTime.of(2014, 3, 22, 1, 0, 0, 0, ZoneOffset.UTC).toEpochSecond();
assertEquals(expected, toEpochSeconds("2014-03-22 01", "y-M-d HH"));
}
public void testToEpochSeconds_GivenPatternHasFullDateAndTimeWithoutTimeZone() {
long expected = ZonedDateTime.of(1985, 8, 18, 20, 15, 40, 0, ZoneOffset.UTC).toEpochSecond();
assertEquals(expected, toEpochSeconds("1985-08-18 20:15:40", "yyyy-MM-dd HH:mm:ss"));
expected = ZonedDateTime.of(1985, 8, 18, 20, 15, 40, 0, ZoneOffset.MIN).toEpochSecond();
assertEquals(expected, toEpochSeconds("1985-08-18 20:15:40", "yyyy-MM-dd HH:mm:ss", ZoneOffset.MIN));
expected = ZonedDateTime.of(1985, 8, 18, 20, 15, 40, 0, ZoneOffset.MAX).toEpochSecond();
assertEquals(expected, toEpochSeconds("1985-08-18 20:15:40", "yyyy-MM-dd HH:mm:ss", ZoneOffset.MAX));
}
public void testToEpochSeconds_GivenPatternHasFullDateAndTimeWithTimeZone() {
assertEquals(1395703820, toEpochSeconds("2014-03-25 01:30:20 +02:00", "yyyy-MM-dd HH:mm:ss XXX"));
}
public void testToEpochSeconds_GivenTimestampRequiresLenientParsing() {
assertEquals(1395703820, toEpochSeconds("2014-03-25 1:30:20 +02:00", "yyyy-MM-dd HH:mm:ss XXX"));
}
public void testToEpochSeconds_GivenPatternHasDateWithoutYearAndTimeWithoutTimeZone() throws ParseException {
// Summertime
long expected = ZonedDateTime.of(LocalDate.now(ZoneOffset.UTC).getYear(), 8, 14, 1, 30, 20, 0, ZoneOffset.UTC).toEpochSecond();
assertEquals(expected, toEpochSeconds("08 14 01:30:20", "MM dd HH:mm:ss"));
// Non-summertime
expected = ZonedDateTime.of(LocalDate.now(ZoneOffset.UTC).getYear(), 12, 14, 1, 30, 20, 0, ZoneOffset.UTC).toEpochSecond();
assertEquals(expected, toEpochSeconds("12 14 01:30:20", "MM dd HH:mm:ss"));
}
public void testToEpochMillis_GivenPatternHasFullDateAndTimeWithTimeZone() {
assertEquals(1395703820542L, toEpochMillis("2014-03-25 01:30:20.542 +02:00", "yyyy-MM-dd HH:mm:ss.SSS XXX"));
}
private static long toEpochSeconds(String timestamp, String pattern) {
TimestampConverter formatter = DateTimeFormatterTimestampConverter.ofPattern(pattern, ZoneOffset.UTC);
return formatter.toEpochSeconds(timestamp);
}
private static long toEpochSeconds(String timestamp, String pattern, ZoneId defaultTimezone) {
TimestampConverter formatter = DateTimeFormatterTimestampConverter.ofPattern(pattern, defaultTimezone);
return formatter.toEpochSeconds(timestamp);
}
private static long toEpochMillis(String timestamp, String pattern) {
TimestampConverter formatter = DateTimeFormatterTimestampConverter.ofPattern(pattern, ZoneOffset.UTC);
return formatter.toEpochMillis(timestamp);
}
}
| DateTimeFormatterTimestampConverterTests |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/error/ShouldBeSymbolicLink_create_Test.java | {
"start": 943,
"end": 1321
} | class ____ {
@Test
void should_create_error_message() {
// GIVEN
final Path actual = mock(Path.class);
// WHEN
String actualMessage = shouldBeSymbolicLink(actual).create(new TextDescription("Test"));
// THEN
then(actualMessage).isEqualTo("[Test] %nExpecting path:%n %s%nto be a symbolic link.".formatted(actual));
}
}
| ShouldBeSymbolicLink_create_Test |
java | apache__logging-log4j2 | log4j-core-test/src/main/java/org/apache/logging/log4j/core/test/net/mock/MockUdpSyslogServer.java | {
"start": 1016,
"end": 2842
} | class ____ extends MockSyslogServer {
private final DatagramSocket socket;
private volatile boolean shutdown = false;
private Thread thread;
public MockUdpSyslogServer(final int numberOfMessagesToReceive, final int port) throws SocketException {
this(port);
}
public MockUdpSyslogServer() throws SocketException {
this(0);
}
private MockUdpSyslogServer(final int port) throws SocketException {
super(0, port);
this.socket = new DatagramSocket(port);
}
@Override
public int getLocalPort() {
return socket.getLocalPort();
}
@Override
public void shutdown() {
this.shutdown = true;
if (socket != null) {
socket.close();
}
if (thread != null) {
thread.interrupt();
try {
thread.join(100);
} catch (final InterruptedException e) {
LOGGER.error("Shutdown of {} thread failed.", getName(), e);
}
}
}
@Override
public void run() {
LOGGER.info("{} started on port {}.", getName(), getLocalPort());
this.thread = Thread.currentThread();
final byte[] bytes = new byte[4096];
final DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
try {
while (!shutdown) {
socket.receive(packet);
final String message = new String(packet.getData(), 0, packet.getLength());
LOGGER.debug("{} received a message: {}", getName(), message);
messageList.add(message);
}
} catch (final Exception e) {
if (!shutdown) {
Throwables.rethrow(e);
}
}
LOGGER.info("{} stopped.", getName());
}
}
| MockUdpSyslogServer |
java | elastic__elasticsearch | test/x-content/src/main/java/org/elasticsearch/test/xcontent/AbstractSchemaValidationTestCase.java | {
"start": 1682,
"end": 7142
} | class ____<T extends ToXContent> extends ESTestCase {
protected static final int NUMBER_OF_TEST_RUNS = 20;
public final void testSchema() throws IOException {
ObjectMapper mapper = new ObjectMapper();
SchemaValidatorsConfig config = new SchemaValidatorsConfig();
JsonSchemaFactory factory = initializeSchemaFactory();
Path p = getDataPath(getSchemaLocation() + getJsonSchemaFileName());
logger.debug("loading schema from: [{}]", p);
JsonSchema jsonSchema = factory.getSchema(mapper.readTree(Files.newInputStream(p)), config);
// ensure the schema meets certain criteria like not empty, strictness
assertTrue("found empty schema", jsonSchema.getValidators().size() > 0);
assertTrue("schema lacks at least 1 required field", jsonSchema.hasRequiredValidator());
assertSchemaStrictness(jsonSchema.getValidators().values(), jsonSchema.getSchemaPath());
for (int runs = 0; runs < NUMBER_OF_TEST_RUNS; runs++) {
BytesReference xContent = XContentHelper.toXContent(createTestInstance(), XContentType.JSON, getToXContentParams(), false);
JsonNode jsonTree = mapper.readTree(xContent.streamInput());
Set<ValidationMessage> errors = jsonSchema.validate(jsonTree);
assertThat("Schema validation failed for: " + jsonTree.toPrettyString(), errors, is(empty()));
}
}
/**
* Creates a random instance to use in the schema tests.
* Override this method to return the random instance that you build
* which must implement {@link ToXContent}.
*/
protected abstract T createTestInstance();
/**
* Return the filename of the schema file used for testing.
*/
protected abstract String getJsonSchemaFileName();
/**
* Params that have to be provided when calling {@link ToXContent#toXContent(XContentBuilder, ToXContent.Params)}
*/
protected ToXContent.Params getToXContentParams() {
return ToXContent.EMPTY_PARAMS;
}
/**
* Root folder for all schema files.
*/
protected String getSchemaLocation() {
return "/rest-api-spec/schema/";
}
/**
* Version of the Json Schema Spec to be used by the test.
*/
protected SpecVersion.VersionFlag getSchemaVersion() {
return SpecVersion.VersionFlag.V7;
}
/**
* Loader for the schema factory.
*
* Uses the ootb factory but replaces the loader for sub schema's stored on the file system.
*/
private JsonSchemaFactory initializeSchemaFactory() {
JsonSchemaFactory factory = JsonSchemaFactory.builder(JsonSchemaFactory.getInstance(getSchemaVersion())).uriFetcher(uri -> {
String fileName = uri.toString().substring(uri.getScheme().length() + 1);
Path path = getDataPath(getSchemaLocation() + fileName);
logger.debug("loading sub-schema [{}] from: [{}]", uri, path);
return Files.newInputStream(path);
}, "file").build();
return factory;
}
/**
* Enforce that the schema as well as all sub schemas define all properties.
*
* This uses an implementation detail of the schema validation library: If
* strict validation is turned on (`"additionalProperties": false`), the schema
* validator injects an instance of AdditionalPropertiesValidator.
*
* The check loops through the validator tree and checks for instances of
* AdditionalPropertiesValidator. If it is absent at expected places the test fails.
*
* Note: we might not catch all places, but at least it works for nested objects and
* array items.
*/
private static void assertSchemaStrictness(Collection<JsonValidator> validatorSet, String path) {
boolean additionalPropertiesValidatorFound = false;
boolean subSchemaFound = false;
for (JsonValidator validator : validatorSet) {
if (validator instanceof PropertiesValidator propertiesValidator) {
subSchemaFound = true;
for (Entry<String, JsonSchema> subSchema : propertiesValidator.getSchemas().entrySet()) {
assertSchemaStrictness(subSchema.getValue().getValidators().values(), propertiesValidator.getSchemaPath());
}
} else if (validator instanceof ItemsValidator itemValidator) {
if (itemValidator.getSchema() != null) {
assertSchemaStrictness(itemValidator.getSchema().getValidators().values(), itemValidator.getSchemaPath());
}
if (itemValidator.getTupleSchema() != null) {
for (JsonSchema subSchema : itemValidator.getTupleSchema()) {
assertSchemaStrictness(subSchema.getValidators().values(), itemValidator.getSchemaPath());
}
}
} else if (validator instanceof AdditionalPropertiesValidator) {
additionalPropertiesValidatorFound = true;
}
}
// if not a leaf, additional property strictness must be set
assertTrue(
"the schema must have additional properties set to false (\"additionalProperties\": false) in all (sub) schemas, "
+ "missing at least for path: "
+ path,
subSchemaFound == false || additionalPropertiesValidatorFound
);
}
}
| AbstractSchemaValidationTestCase |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/engine/spi/LoadQueryInfluencersTest.java | {
"start": 1472,
"end": 3681
} | class ____ {
@Test
public void usesCustomEntityBatchSizeForEffectivelyBatchLoadable(SessionFactoryScope scope) {
scope.inSession(
(nonTransactedSession) -> {
LoadQueryInfluencers influencers = new LoadQueryInfluencers( nonTransactedSession.getSessionFactory() );
assertTrue( influencers.getBatchSize() > 1, "Expecting default batch size > 1" );
EntityPersister persister = nonTransactedSession.getSessionFactory()
.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( EntityWithBatchSize1.class );
assertFalse( persister.isBatchLoadable(), "Incorrect persister batch loadable." );
assertEquals( 1, influencers.effectiveBatchSize( persister ), "Incorrect effective batch size." );
assertFalse(
influencers.effectivelyBatchLoadable( persister ),
"Incorrect effective batch loadable."
);
}
);
}
@Test
public void usesCustomCollectionBatchSizeForEffectivelyBatchLoadable(SessionFactoryScope scope) {
scope.inSession(
(nonTransactedSession) -> {
LoadQueryInfluencers influencers = new LoadQueryInfluencers( nonTransactedSession.getSessionFactory() );
assertTrue( influencers.getBatchSize() > 1, "Expecting default batch size > 1" );
EntityPersister entityPersister = nonTransactedSession.getSessionFactory()
.getRuntimeMetamodels()
.getMappingMetamodel()
.getEntityDescriptor( EntityWithBatchSize1.class );
NavigableRole collectionRole = entityPersister.getNavigableRole()
.append( "childrenWithBatchSize1" );
CollectionPersister persister = nonTransactedSession.getSessionFactory()
.getRuntimeMetamodels()
.getMappingMetamodel()
.findCollectionDescriptor( collectionRole.getFullPath() );
assertFalse( persister.isBatchLoadable(), "Incorrect persister batch loadable." );
assertEquals( 1, influencers.effectiveBatchSize( persister ), "Incorrect effective batch size." );
assertFalse(
influencers.effectivelyBatchLoadable( persister ),
"Incorrect effective batch loadable."
);
}
);
}
@Entity
@Table(name = "EntityWithBatchSize1")
@BatchSize(size = 1)
public | LoadQueryInfluencersTest |
java | hibernate__hibernate-orm | hibernate-jcache/src/test/java/org/hibernate/orm/test/jcache/domain/EventManager.java | {
"start": 488,
"end": 6630
} | class ____ {
private final SessionFactory sessionFactory;
public EventManager(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List listEmailsOfEvent(Long eventId) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
List emailList = new ArrayList();
Event event = (Event)session.getReference(Event.class, eventId);
for (Iterator it = event.getParticipants().iterator(); it.hasNext(); ) {
Person person = (Person)it.next();
emailList.addAll(person.getEmailAddresses());
}
session.getTransaction().commit();
return emailList;
}
public Long createAndStoreEvent(String title, Person organizer, Date theDate) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
theEvent.setOrganizer(organizer);
session.persist( theEvent );
session.getTransaction().commit();
return theEvent.getId();
}
public Long createAndStorePerson(String firstName, String lastName) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person person = new Person();
person.setFirstname(firstName);
person.setLastname(lastName);
session.persist(person);
session.getTransaction().commit();
return person.getId();
}
public Long createAndStorePerson(Person person) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.persist(person);
session.getTransaction().commit();
return person.getId();
}
public List listEvents() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
List result = session.createQuery("from Event").setCacheable(true).list();
session.getTransaction().commit();
return result;
}
/**
* Call setEntity() on a cacheable query - see FORGE-265
*/
public List listEventsOfOrganizer(Person organizer) {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
Query query = session.createQuery( "from Event ev where ev.organizer = :organizer" );
query.setCacheable( true );
query.setParameter( "organizer", organizer );
List result = query.list();
session.getTransaction().commit();
return result;
}
catch (Exception e){
if(session.getTransaction().isActive()){
session.getTransaction().rollback();
}
throw e;
}
}
/**
* Use a Criteria query - see FORGE-247
*/
public List listEventsWithCriteria() {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Event> criteria = criteriaBuilder.createQuery( Event.class );
criteria.from( Event.class );
List<Event> result = session.createQuery( criteria ).setCacheable( true ).list();
// List result = session.createCriteria( Event.class )
// .setCacheable( true )
// .list();
session.getTransaction().commit();
return result;
}
catch (Exception e){
if(session.getTransaction().isActive()){
session.getTransaction().rollback();
}
throw e;
}
}
public void addPersonToEvent(Long personId, Long eventId) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person aPerson = (Person)session.getReference(Person.class, personId);
Event anEvent = (Event)session.getReference(Event.class, eventId);
aPerson.getEvents().add(anEvent);
session.getTransaction().commit();
}
public Long addPersonToAccount(Long personId, Account account) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person aPerson = (Person)session.getReference(Person.class, personId);
account.setPerson(aPerson);
session.persist(account);
session.getTransaction().commit();
return account.getId();
}
public Account getAccount(Long accountId) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Account account = (Account)session.getReference(Account.class, accountId);
session.getTransaction().commit();
return account;
}
public void addEmailToPerson(Long personId, String emailAddress) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person aPerson = (Person)session.getReference(Person.class, personId);
// The getEmailAddresses() might trigger a lazy load of the collection
aPerson.getEmailAddresses().add(emailAddress);
session.getTransaction().commit();
}
public void addPhoneNumberToPerson(Long personId, PhoneNumber pN) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person aPerson = (Person)session.getReference(Person.class, personId);
pN.setPersonId(personId.longValue());
aPerson.getPhoneNumbers().add(pN);
session.getTransaction().commit();
}
public void addTalismanToPerson(Long personId, String talisman) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Person aPerson = (Person)session.getReference(Person.class, personId);
aPerson.addTalisman(talisman);
session.getTransaction().commit();
}
public Long createHolidayCalendar() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
// delete all existing calendars
List calendars = session.createQuery("from HolidayCalendar").setCacheable(true).list();
for (ListIterator li = calendars.listIterator(); li.hasNext(); ) {
session.remove(li.next());
}
HolidayCalendar calendar = new HolidayCalendar();
calendar.init();
session.persist(calendar);
session.getTransaction().commit();
return calendar.getId();
}
public HolidayCalendar getHolidayCalendar() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
List calendars = session.createQuery("from HolidayCalendar").setCacheable(true).list();
session.getTransaction().commit();
return calendars.isEmpty() ? null : (HolidayCalendar)calendars.get(0);
}
}
| EventManager |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/transaction/batch/AbstractJtaBatchTest.java | {
"start": 1550,
"end": 1944
} | class ____ {
private Long id;
private String message;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
@Entity(name = "EventLog")
public static | Comment |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-data-r2dbc-liquibase/src/dockerTest/java/smoketest/data/r2dbc/CityRepositoryTests.java | {
"start": 1458,
"end": 1982
} | class ____ {
@Container
@ServiceConnection
static PostgreSQLContainer postgresql = TestImage.container(PostgreSQLContainer.class)
.withDatabaseName("test_liquibase");
@Autowired
private CityRepository repository;
@Test
void databaseHasBeenInitialized() {
StepVerifier.create(this.repository.findByState("DC").filter((city) -> city.getName().equals("Washington")))
.consumeNextWith((city) -> assertThat(city.getId()).isNotNull())
.expectComplete()
.verify(Duration.ofSeconds(30));
}
}
| CityRepositoryTests |
java | grpc__grpc-java | examples/src/main/java/io/grpc/examples/hedging/HedgingHelloWorldServer.java | {
"start": 1273,
"end": 2996
} | class ____ {
private static final Logger logger = Logger.getLogger(HedgingHelloWorldServer.class.getName());
private Server server;
private void start() throws IOException {
/* The port on which the server should run */
int port = 50051;
server = Grpc.newServerBuilderForPort(port, InsecureServerCredentials.create())
.addService(new GreeterImpl())
.intercept(new LatencyInjectionInterceptor())
.build()
.start();
logger.info("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
try {
HedgingHelloWorldServer.this.stop();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
System.err.println("*** server shut down");
}
});
}
private void stop() throws InterruptedException {
if (server != null) {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
}
}
/**
* Await termination on the main thread since the grpc library uses daemon threads.
*/
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
/**
* Main launches the server from the command line.
*/
public static void main(String[] args) throws IOException, InterruptedException {
final HedgingHelloWorldServer server = new HedgingHelloWorldServer();
server.start();
server.blockUntilShutdown();
}
static | HedgingHelloWorldServer |
java | quarkusio__quarkus | extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/ReactiveTransactionalStringCommandsImpl.java | {
"start": 500,
"end": 7083
} | class ____<K, V> extends AbstractTransactionalCommands
implements ReactiveTransactionalStringCommands<K, V>, ReactiveTransactionalValueCommands<K, V> {
private final ReactiveStringCommandsImpl<K, V> reactive;
public ReactiveTransactionalStringCommandsImpl(ReactiveTransactionalRedisDataSource ds,
ReactiveStringCommandsImpl<K, V> reactive, TransactionHolder tx) {
super(ds, tx);
this.reactive = reactive;
}
@Override
public Uni<Void> append(K key, V value) {
this.tx.enqueue(Response::toLong);
return this.reactive._append(key, value).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> decr(K key) {
this.tx.enqueue(Response::toLong);
return this.reactive._decr(key).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> decrby(K key, long amount) {
this.tx.enqueue(Response::toLong);
return this.reactive._decrby(key, amount).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> get(K key) {
this.tx.enqueue(this.reactive::decodeV);
return this.reactive._get(key).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> getdel(K key) {
this.tx.enqueue(this.reactive::decodeV);
return this.reactive._getdel(key).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> getex(K key, GetExArgs args) {
this.tx.enqueue(this.reactive::decodeV);
return this.reactive._getex(key, args).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> getex(K key, io.quarkus.redis.datasource.value.GetExArgs args) {
this.tx.enqueue(this.reactive::decodeV);
return this.reactive._getex(key, args).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> getrange(K key, long start, long end) {
this.tx.enqueue(Response::toString);
return this.reactive._getrange(key, start, end).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> getset(K key, V value) {
this.tx.enqueue(this.reactive::decodeV);
return this.reactive._getset(key, value).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> incr(K key) {
this.tx.enqueue(Response::toLong);
return this.reactive._incr(key).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> incrby(K key, long amount) {
this.tx.enqueue(Response::toLong);
return this.reactive._incrby(key, amount).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> incrbyfloat(K key, double amount) {
this.tx.enqueue(Response::toDouble);
return this.reactive._incrbyfloat(key, amount).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> lcs(K key1, K key2) {
this.tx.enqueue(Response::toString);
return this.reactive._lcs(key1, key2).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> lcsLength(K key1, K key2) {
this.tx.enqueue(Response::toLong);
return this.reactive._lcsLength(key1, key2).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> mget(K... keys) {
this.tx.enqueue(resp -> this.reactive.decodeAsOrderedMap(resp, keys));
return this.reactive._mget(keys).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> mset(Map<K, V> map) {
this.tx.enqueue(resp -> null);
return this.reactive._mset(map).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> msetnx(Map<K, V> map) {
this.tx.enqueue(Response::toBoolean);
return this.reactive._msetnx(map).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> psetex(K key, long milliseconds, V value) {
this.tx.enqueue(resp -> null);
return this.reactive._psetex(key, milliseconds, value).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> set(K key, V value) {
this.tx.enqueue(resp -> null);
return this.reactive._set(key, value).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> set(K key, V value, SetArgs setArgs) {
this.tx.enqueue(resp -> null);
return this.reactive._set(key, value, setArgs).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> set(K key, V value, io.quarkus.redis.datasource.value.SetArgs setArgs) {
this.tx.enqueue(resp -> null);
return this.reactive._set(key, value, setArgs).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> setGet(K key, V value) {
this.tx.enqueue(this.reactive::decodeV);
return this.reactive._setGet(key, value).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> setGet(K key, V value, SetArgs setArgs) {
this.tx.enqueue(this.reactive::decodeV);
return this.reactive._setGet(key, value, setArgs).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> setGet(K key, V value, io.quarkus.redis.datasource.value.SetArgs setArgs) {
this.tx.enqueue(this.reactive::decodeV);
return this.reactive._setGet(key, value, setArgs).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> setex(K key, long seconds, V value) {
this.tx.enqueue(resp -> null);
return this.reactive._setex(key, seconds, value).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> setnx(K key, V value) {
this.tx.enqueue(Response::toBoolean);
return this.reactive._setnx(key, value).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> setrange(K key, long offset, V value) {
this.tx.enqueue(Response::toLong);
return this.reactive._setrange(key, offset, value).invoke(this::queuedOrDiscard).replaceWithVoid();
}
@Override
public Uni<Void> strlen(K key) {
this.tx.enqueue(Response::toLong);
return this.reactive._strlen(key).invoke(this::queuedOrDiscard).replaceWithVoid();
}
}
| ReactiveTransactionalStringCommandsImpl |
java | elastic__elasticsearch | modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/DatabaseNodeServiceTests.java | {
"start": 5100,
"end": 26274
} | class ____ extends ESTestCase {
private Client client;
private ProjectClient projectClient;
private Path geoIpTmpDir;
private ThreadPool threadPool;
private DatabaseNodeService databaseNodeService;
private ResourceWatcherService resourceWatcherService;
private IngestService ingestService;
private ClusterService clusterService;
private ProjectId projectId;
private ProjectResolver projectResolver;
private final Collection<Releasable> toRelease = new CopyOnWriteArrayList<>();
@Before
public void setup() throws IOException {
// cover for multi-project enable/disabled
boolean multiProject = randomBoolean();
projectId = multiProject ? randomProjectIdOrDefault() : ProjectId.DEFAULT;
projectResolver = multiProject ? TestProjectResolvers.singleProject(projectId) : TestProjectResolvers.DEFAULT_PROJECT_ONLY;
final Path geoIpConfigDir = createTempDir();
GeoIpCache cache = new GeoIpCache(1000);
ConfigDatabases configDatabases = new ConfigDatabases(geoIpConfigDir, cache);
copyDefaultDatabases(geoIpConfigDir, configDatabases);
threadPool = new TestThreadPool(ConfigDatabases.class.getSimpleName());
Settings settings = Settings.builder().put("resource.reload.interval.high", TimeValue.timeValueMillis(100)).build();
resourceWatcherService = new ResourceWatcherService(settings, threadPool);
projectClient = mock(ProjectClient.class);
client = mock(Client.class);
when(client.projectClient(any())).thenReturn(projectClient);
ingestService = mock(IngestService.class);
clusterService = mock(ClusterService.class);
geoIpTmpDir = createTempDir();
databaseNodeService = new DatabaseNodeService(
geoIpTmpDir,
client,
cache,
configDatabases,
Runnable::run,
clusterService,
ingestService,
projectResolver
);
databaseNodeService.initialize("nodeId", resourceWatcherService);
}
@After
public void cleanup() {
resourceWatcherService.close();
threadPool.shutdownNow();
Releasables.close(toRelease);
toRelease.clear();
verify(client, Mockito.atLeast(0)).projectClient(any());
verifyNoMoreInteractions(client);
}
public void testCheckDatabases() throws Exception {
String md5 = mockSearches("GeoIP2-City.mmdb", 5, 14);
String taskId = getTaskId(projectId, projectResolver.supportsMultipleProjects());
PersistentTask<?> task = new PersistentTask<>(taskId, GeoIpDownloader.GEOIP_DOWNLOADER, new GeoIpTaskParams(), 1, null);
task = new PersistentTask<>(task, new GeoIpTaskState(Map.of("GeoIP2-City.mmdb", new GeoIpTaskState.Metadata(10, 5, 14, md5, 10))));
PersistentTasksCustomMetadata tasksCustomMetadata = new PersistentTasksCustomMetadata(1L, Map.of(taskId, task));
ClusterState state = createClusterState(projectId, tasksCustomMetadata);
int numPipelinesToBeReloaded = randomInt(4);
List<String> pipelineIds = IntStream.range(0, numPipelinesToBeReloaded).mapToObj(String::valueOf).toList();
when(ingestService.getPipelineWithProcessorType(any(), any(), any())).thenReturn(pipelineIds);
assertThat(databaseNodeService.getDatabase(projectId, "GeoIP2-City.mmdb"), nullValue());
// Nothing should be downloaded, since the database is no longer valid (older than 30 days)
databaseNodeService.checkDatabases(state);
DatabaseReaderLazyLoader database = databaseNodeService.getDatabaseReaderLazyLoader(projectId, "GeoIP2-City.mmdb");
assertThat(database, nullValue());
verify(projectClient, times(0)).search(any());
verify(ingestService, times(0)).reloadPipeline(any(), anyString());
try (Stream<Path> files = Files.list(geoIpTmpDir.resolve("geoip-databases").resolve("nodeId"))) {
assertEquals(0, files.count());
}
task = new PersistentTask<>(
task,
new GeoIpTaskState(Map.of("GeoIP2-City.mmdb", new GeoIpTaskState.Metadata(10, 5, 14, md5, System.currentTimeMillis())))
);
tasksCustomMetadata = new PersistentTasksCustomMetadata(1L, Map.of(taskId, task));
state = createClusterState(projectId, tasksCustomMetadata);
// Database should be downloaded
databaseNodeService.checkDatabases(state);
database = databaseNodeService.getDatabaseReaderLazyLoader(projectId, "GeoIP2-City.mmdb");
assertThat(database, notNullValue());
verify(projectClient, times(10)).search(any());
try (Stream<Path> files = Files.list(geoIpTmpDir.resolve("geoip-databases").resolve("nodeId"))) {
assertThat(files.count(), greaterThanOrEqualTo(1L));
}
// First time GeoIP2-City.mmdb is downloaded, so a pipeline reload can happen:
verify(ingestService, times(numPipelinesToBeReloaded)).reloadPipeline(any(), anyString());
// 30 days check passed but we mocked mmdb data so parsing will fail
expectThrows(InvalidDatabaseException.class, database::get);
}
public void testCheckDatabases_dontCheckDatabaseOnNonIngestNode() throws Exception {
String md5 = mockSearches("GeoIP2-City.mmdb", 0, 9);
String taskId = getTaskId(projectId, projectResolver.supportsMultipleProjects());
PersistentTask<?> task = new PersistentTask<>(taskId, GeoIpDownloader.GEOIP_DOWNLOADER, new GeoIpTaskParams(), 1, null);
task = new PersistentTask<>(task, new GeoIpTaskState(Map.of("GeoIP2-City.mmdb", new GeoIpTaskState.Metadata(0L, 0, 9, md5, 10))));
PersistentTasksCustomMetadata tasksCustomMetadata = new PersistentTasksCustomMetadata(1L, Map.of(taskId, task));
ClusterState state = ClusterState.builder(createClusterState(projectId, tasksCustomMetadata))
.nodes(
new DiscoveryNodes.Builder().add(
DiscoveryNodeUtils.builder("_id1").name("_name1").roles(Set.of(DiscoveryNodeRole.MASTER_ROLE)).build()
).localNodeId("_id1")
)
.build();
databaseNodeService.checkDatabases(state);
assertThat(databaseNodeService.getDatabase(projectId, "GeoIP2-City.mmdb"), nullValue());
verify(projectClient, never()).search(any());
try (Stream<Path> files = Files.list(geoIpTmpDir.resolve("geoip-databases").resolve("nodeId"))) {
assertThat(files.toList(), empty());
}
}
public void testCheckDatabases_dontCheckDatabaseWhenNoDatabasesIndex() throws Exception {
String md5 = mockSearches("GeoIP2-City.mmdb", 0, 9);
String taskId = getTaskId(projectId, projectResolver.supportsMultipleProjects());
PersistentTask<?> task = new PersistentTask<>(taskId, GeoIpDownloader.GEOIP_DOWNLOADER, new GeoIpTaskParams(), 1, null);
task = new PersistentTask<>(task, new GeoIpTaskState(Map.of("GeoIP2-City.mmdb", new GeoIpTaskState.Metadata(0L, 0, 9, md5, 10))));
PersistentTasksCustomMetadata tasksCustomMetadata = new PersistentTasksCustomMetadata(1L, Map.of(taskId, task));
ClusterState state = ClusterState.builder(new ClusterName("name"))
.putProjectMetadata(ProjectMetadata.builder(projectId).putCustom(TYPE, tasksCustomMetadata))
.nodes(new DiscoveryNodes.Builder().add(DiscoveryNodeUtils.create("_id1")).localNodeId("_id1"))
.build();
databaseNodeService.checkDatabases(state);
assertThat(databaseNodeService.getDatabase(projectId, "GeoIP2-City.mmdb"), nullValue());
verify(projectClient, never()).search(any());
try (Stream<Path> files = Files.list(geoIpTmpDir.resolve("geoip-databases").resolve("nodeId"))) {
assertThat(files.toList(), empty());
}
}
public void testCheckDatabases_dontCheckDatabaseWhenGeoIpDownloadTask() throws Exception {
PersistentTasksCustomMetadata tasksCustomMetadata = new PersistentTasksCustomMetadata(0L, Map.of());
ClusterState state = createClusterState(projectId, tasksCustomMetadata);
mockSearches("GeoIP2-City.mmdb", 0, 9);
databaseNodeService.checkDatabases(state);
assertThat(databaseNodeService.getDatabase(projectId, "GeoIP2-City.mmdb"), nullValue());
verify(projectClient, never()).search(any());
try (Stream<Path> files = Files.list(geoIpTmpDir.resolve("geoip-databases").resolve("nodeId"))) {
assertThat(files.toList(), empty());
}
}
public void testRetrieveDatabase() throws Exception {
String md5 = mockSearches("_name", 0, 29);
GeoIpTaskState.Metadata metadata = new GeoIpTaskState.Metadata(-1, 0, 29, md5, 10);
@SuppressWarnings("unchecked")
CheckedConsumer<byte[], IOException> chunkConsumer = mock(CheckedConsumer.class);
@SuppressWarnings("unchecked")
CheckedRunnable<Exception> completedHandler = mock(CheckedRunnable.class);
@SuppressWarnings("unchecked")
Consumer<Exception> failureHandler = mock(Consumer.class);
databaseNodeService.retrieveDatabase(projectId, "_name", md5, metadata, chunkConsumer, completedHandler, failureHandler);
verify(failureHandler, never()).accept(any());
verify(chunkConsumer, times(30)).accept(any());
verify(completedHandler, times(1)).run();
verify(projectClient, times(30)).search(any());
}
public void testRetrieveDatabaseCorruption() throws Exception {
String md5 = mockSearches("_name", 0, 9);
String incorrectMd5 = "different";
GeoIpTaskState.Metadata metadata = new GeoIpTaskState.Metadata(-1, 0, 9, incorrectMd5, 10);
@SuppressWarnings("unchecked")
CheckedConsumer<byte[], IOException> chunkConsumer = mock(CheckedConsumer.class);
@SuppressWarnings("unchecked")
CheckedRunnable<Exception> completedHandler = mock(CheckedRunnable.class);
@SuppressWarnings("unchecked")
Consumer<Exception> failureHandler = mock(Consumer.class);
databaseNodeService.retrieveDatabase(projectId, "_name", incorrectMd5, metadata, chunkConsumer, completedHandler, failureHandler);
ArgumentCaptor<Exception> exceptionCaptor = ArgumentCaptor.forClass(Exception.class);
verify(failureHandler, times(1)).accept(exceptionCaptor.capture());
assertThat(exceptionCaptor.getAllValues().size(), equalTo(1));
assertThat(
exceptionCaptor.getAllValues().get(0).getMessage(),
equalTo("expected md5 hash [different], " + "but got md5 hash [" + md5 + "]")
);
verify(chunkConsumer, times(10)).accept(any());
verify(completedHandler, times(0)).run();
verify(projectClient, times(10)).search(any());
}
public void testUpdateDatabase() throws Exception {
int numPipelinesToBeReloaded = randomInt(4);
List<String> pipelineIds = IntStream.range(0, numPipelinesToBeReloaded).mapToObj(String::valueOf).toList();
when(ingestService.getPipelineWithProcessorType(any(), any(), any())).thenReturn(pipelineIds);
databaseNodeService.updateDatabase(projectId, "_name", "_md5", geoIpTmpDir.resolve("some-file"));
// Updating the first time may trigger a reload.
verify(clusterService, times(1)).addListener(any());
verify(ingestService, times(1)).getPipelineWithProcessorType(any(), any(), any());
verify(ingestService, times(numPipelinesToBeReloaded)).reloadPipeline(any(), anyString());
verifyNoMoreInteractions(clusterService);
verifyNoMoreInteractions(ingestService);
reset(clusterService);
reset(ingestService);
// Subsequent updates shouldn't trigger a reload.
databaseNodeService.updateDatabase(projectId, "_name", "_md5", geoIpTmpDir.resolve("some-file"));
verifyNoMoreInteractions(clusterService);
verifyNoMoreInteractions(ingestService);
}
private String mockSearches(String databaseName, int firstChunk, int lastChunk) throws IOException {
String dummyContent = "test: " + databaseName;
List<byte[]> data;
// We want to make sure we handle gzip files or plain mmdb files equally well:
if (randomBoolean()) {
data = gzip(databaseName, dummyContent, lastChunk - firstChunk + 1);
assertThat(gunzip(data), equalTo(dummyContent));
} else {
data = chunkBytes(dummyContent, lastChunk - firstChunk + 1);
assertThat(unchunkBytes(data), equalTo(dummyContent));
}
Map<String, ActionFuture<SearchResponse>> requestMap = new HashMap<>();
for (int i = firstChunk; i <= lastChunk; i++) {
byte[] chunk;
if (i - firstChunk < data.size()) {
chunk = data.get(i - firstChunk);
} else {
chunk = new byte[0]; // We had so little data that the chunk(s) at the end will be empty
}
SearchHit hit = SearchHit.unpooled(i);
try (XContentBuilder builder = XContentBuilder.builder(XContentType.SMILE.xContent())) {
builder.map(Map.of("data", chunk));
builder.flush();
ByteArrayOutputStream outputStream = (ByteArrayOutputStream) builder.getOutputStream();
hit.sourceRef(new BytesArray(outputStream.toByteArray()));
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
SearchHits hits = SearchHits.unpooled(new SearchHit[] { hit }, new TotalHits(1, TotalHits.Relation.EQUAL_TO), 1f);
SearchResponse searchResponse = SearchResponseUtils.successfulResponse(hits);
toRelease.add(searchResponse::decRef);
@SuppressWarnings("unchecked")
ActionFuture<SearchResponse> actionFuture = mock(ActionFuture.class);
when(actionFuture.actionGet()).thenAnswer((Answer<SearchResponse>) invocation -> {
searchResponse.incRef();
return searchResponse;
});
requestMap.put(databaseName + "_" + i, actionFuture);
}
when(projectClient.search(any())).thenAnswer(invocationOnMock -> {
SearchRequest req = (SearchRequest) invocationOnMock.getArguments()[0];
TermQueryBuilder term = (TermQueryBuilder) req.source().query();
String id = (String) term.value();
return requestMap.get(id.substring(0, id.lastIndexOf('_')));
});
MessageDigest md = MessageDigests.md5();
data.forEach(md::update);
return MessageDigests.toHexString(md.digest());
}
static ClusterState createClusterState(ProjectId projectId, PersistentTasksCustomMetadata tasksCustomMetadata) {
return createClusterState(projectId, tasksCustomMetadata, false);
}
static ClusterState createClusterState(
ProjectId projectId,
PersistentTasksCustomMetadata tasksCustomMetadata,
boolean noStartedShards
) {
boolean aliasGeoipDatabase = randomBoolean();
String indexName = aliasGeoipDatabase
? GeoIpDownloader.DATABASES_INDEX + "-" + randomAlphaOfLength(5)
: GeoIpDownloader.DATABASES_INDEX;
Index index = new Index(indexName, UUID.randomUUID().toString());
IndexMetadata.Builder idxMeta = IndexMetadata.builder(index.getName())
.settings(indexSettings(IndexVersion.current(), 1, 0).put("index.uuid", index.getUUID()));
if (aliasGeoipDatabase) {
idxMeta.putAlias(AliasMetadata.builder(GeoIpDownloader.DATABASES_INDEX));
}
ShardRouting shardRouting = ShardRouting.newUnassigned(
new ShardId(index, 0),
true,
RecoverySource.ExistingStoreRecoverySource.INSTANCE,
new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, ""),
ShardRouting.Role.DEFAULT
);
String nodeId = ESTestCase.randomAlphaOfLength(8);
shardRouting = shardRouting.initialize(nodeId, null, shardRouting.getExpectedShardSize());
if (noStartedShards == false) {
shardRouting = shardRouting.moveToStarted(ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE);
}
return ClusterState.builder(new ClusterName("name"))
.putProjectMetadata(ProjectMetadata.builder(projectId).put(idxMeta).putCustom(TYPE, tasksCustomMetadata))
.nodes(DiscoveryNodes.builder().add(DiscoveryNodeUtils.create("_id1")).localNodeId("_id1"))
.putRoutingTable(
projectId,
RoutingTable.builder()
.add(
IndexRoutingTable.builder(index)
.addIndexShard(IndexShardRoutingTable.builder(new ShardId(index, 0)).addShard(shardRouting))
)
.build()
)
.build();
}
private static List<byte[]> chunkBytes(String content, int chunks) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
OutputStream outputStream = byteArrayOutputStream;
byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
outputStream.write(contentBytes);
outputStream.close();
byte[] all = byteArrayOutputStream.toByteArray();
int chunkSize = Math.max(1, all.length / chunks);
List<byte[]> data = new ArrayList<>();
for (int from = 0; from < all.length;) {
int to = from + chunkSize;
if (to > all.length) {
to = all.length;
}
data.add(Arrays.copyOfRange(all, from, to));
from = to;
}
while (data.size() > chunks) {
byte[] last = data.remove(data.size() - 1);
byte[] secondLast = data.remove(data.size() - 1);
byte[] merged = new byte[secondLast.length + last.length];
System.arraycopy(secondLast, 0, merged, 0, secondLast.length);
System.arraycopy(last, 0, merged, secondLast.length, last.length);
data.add(merged);
}
assert data.size() == Math.min(chunks, content.length());
return data;
}
private static List<byte[]> gzip(String name, String content, int chunks) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes);
byte[] header = new byte[512];
byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
byte[] sizeBytes = Strings.format("%1$012o", contentBytes.length).getBytes(StandardCharsets.UTF_8);
System.arraycopy(nameBytes, 0, header, 0, nameBytes.length);
System.arraycopy(sizeBytes, 0, header, 124, 12);
gzipOutputStream.write(header);
gzipOutputStream.write(contentBytes);
gzipOutputStream.write(512 - contentBytes.length);
gzipOutputStream.write(new byte[512]);
gzipOutputStream.write(new byte[512]);
gzipOutputStream.close();
byte[] all = bytes.toByteArray();
int chunkSize = all.length / chunks;
List<byte[]> data = new ArrayList<>();
for (int from = 0; from < all.length;) {
int to = from + chunkSize;
if (to > all.length) {
to = all.length;
}
data.add(Arrays.copyOfRange(all, from, to));
from = to;
}
while (data.size() > chunks) {
byte[] last = data.remove(data.size() - 1);
byte[] secondLast = data.remove(data.size() - 1);
byte[] merged = new byte[secondLast.length + last.length];
System.arraycopy(secondLast, 0, merged, 0, secondLast.length);
System.arraycopy(last, 0, merged, secondLast.length, last.length);
data.add(merged);
}
assert data.size() == chunks;
return data;
}
private static byte[] unchunkBytesToByteArray(List<byte[]> chunks) throws IOException {
byte[] allBytes = new byte[chunks.stream().mapToInt(value -> value.length).sum()];
int written = 0;
for (byte[] chunk : chunks) {
System.arraycopy(chunk, 0, allBytes, written, chunk.length);
written += chunk.length;
}
return allBytes;
}
private static String unchunkBytes(List<byte[]> chunks) throws IOException {
byte[] allBytes = unchunkBytesToByteArray(chunks);
return new String(allBytes, StandardCharsets.UTF_8);
}
private static String gunzip(List<byte[]> chunks) throws IOException {
byte[] gzippedContent = unchunkBytesToByteArray(chunks);
TarInputStream gzipInputStream = new TarInputStream(new GZIPInputStream(new ByteArrayInputStream(gzippedContent)));
gzipInputStream.getNextEntry();
return Streams.readFully(gzipInputStream).utf8ToString();
}
}
| DatabaseNodeServiceTests |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/scope/CreatedBean.java | {
"start": 1107,
"end": 1761
} | interface ____<T> extends Closeable, AutoCloseable {
/**
* @return The bean definition.
*/
BeanDefinition<T> definition();
/**
* @return The bean
*/
@NonNull
T bean();
/**
* Returns an ID that is unique to the bean and can be used to cache the instance if necessary.
*
* @return The id
*/
BeanIdentifier id();
/**
* Destroy the bean entry, performing any shutdown and releasing any dependent objects.
*
* @throws BeanDestructionException If an error occurs closing the created bean.
*/
@Override
void close() throws BeanDestructionException;
}
| CreatedBean |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java | {
"start": 92013,
"end": 92125
} | interface ____ {
String one();
String two();
boolean three();
long four();
}
| OneTwoThreeFour |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/api/windowing/evictors/CountEvictor.java | {
"start": 1282,
"end": 3634
} | class ____<W extends Window> implements Evictor<Object, W> {
private static final long serialVersionUID = 1L;
private final long maxCount;
private final boolean doEvictAfter;
private CountEvictor(long count, boolean doEvictAfter) {
this.maxCount = count;
this.doEvictAfter = doEvictAfter;
}
private CountEvictor(long count) {
this.maxCount = count;
this.doEvictAfter = false;
}
@Override
public void evictBefore(
Iterable<TimestampedValue<Object>> elements, int size, W window, EvictorContext ctx) {
if (!doEvictAfter) {
evict(elements, size, ctx);
}
}
@Override
public void evictAfter(
Iterable<TimestampedValue<Object>> elements, int size, W window, EvictorContext ctx) {
if (doEvictAfter) {
evict(elements, size, ctx);
}
}
private void evict(Iterable<TimestampedValue<Object>> elements, int size, EvictorContext ctx) {
if (size <= maxCount) {
return;
} else {
int evictedCount = 0;
for (Iterator<TimestampedValue<Object>> iterator = elements.iterator();
iterator.hasNext(); ) {
iterator.next();
evictedCount++;
if (evictedCount > size - maxCount) {
break;
} else {
iterator.remove();
}
}
}
}
/**
* Creates a {@code CountEvictor} that keeps the given number of elements. Eviction is done
* before the window function.
*
* @param maxCount The number of elements to keep in the pane.
*/
public static <W extends Window> CountEvictor<W> of(long maxCount) {
return new CountEvictor<>(maxCount);
}
/**
* Creates a {@code CountEvictor} that keeps the given number of elements in the pane Eviction
* is done before/after the window function based on the value of doEvictAfter.
*
* @param maxCount The number of elements to keep in the pane.
* @param doEvictAfter Whether to do eviction after the window function.
*/
public static <W extends Window> CountEvictor<W> of(long maxCount, boolean doEvictAfter) {
return new CountEvictor<>(maxCount, doEvictAfter);
}
}
| CountEvictor |
java | spring-projects__spring-boot | module/spring-boot-data-couchbase/src/test/java/org/springframework/boot/data/couchbase/domain/city/ReactiveCityRepository.java | {
"start": 788,
"end": 919
} | interface ____ extends Repository<City, Long> {
Mono<City> save(City city);
Mono<City> findById(Long id);
}
| ReactiveCityRepository |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/find/ExpressionFactory.java | {
"start": 2068,
"end": 2526
} | class ____ allow an opportunity to register
*/
void registerExpression(Class<? extends Expression> expressionClass) {
try {
Method register = expressionClass.getMethod(REGISTER_EXPRESSION_METHOD,
ExpressionFactory.class);
if (register != null) {
register.invoke(null, this);
}
} catch (Exception e) {
throw new RuntimeException(StringUtils.stringifyException(e));
}
}
/**
* Register the given | to |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/cglib/core/TinyBitSet.java | {
"start": 678,
"end": 1990
} | class ____ {
private static final int[] T = new int[256];
private int value = 0;
private static int gcount(int x) {
int c = 0;
while (x != 0) {
c++;
x &= (x - 1);
}
return c;
}
static {
for (int j = 0; j < 256; j++) {
T[j] = gcount(j);
}
}
private static int topbit(int i) {
int j;
for (j = 0; i != 0; i ^= j) {
j = i & -i;
}
return j;
}
private static int log2(int i) {
int j = 0;
for (j = 0; i != 0; i >>= 1) {
j++;
}
return j;
}
public int length() {
return log2(topbit(value));
}
/**
* If bit 31 is set then this method results in an infinite loop.
*
* @return the number of bits set to <code>true</code> in this TinyBitSet.
*/
public int cardinality() {
int w = value;
int c = 0;
while (w != 0) {
c += T[w & 255];
w >>= 8;
}
return c;
}
public boolean get(int index) {
return (value & (1 << index)) != 0;
}
public void set(int index) {
value |= (1 << index);
}
public void clear(int index) {
value &= ~(1 << index);
}
}
| TinyBitSet |
java | elastic__elasticsearch | modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/FailProcessor.java | {
"start": 1614,
"end": 2546
} | class ____ implements Processor.Factory {
private final ScriptService scriptService;
public Factory(ScriptService scriptService) {
this.scriptService = scriptService;
}
@Override
public FailProcessor create(
Map<String, Processor.Factory> registry,
String processorTag,
String description,
Map<String, Object> config,
ProjectId projectId
) throws Exception {
String message = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "message");
TemplateScript.Factory compiledTemplate = ConfigurationUtils.compileTemplate(
TYPE,
processorTag,
"message",
message,
scriptService
);
return new FailProcessor(processorTag, description, compiledTemplate);
}
}
}
| Factory |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/codec/json/Jackson2CodecSupport.java | {
"start": 5876,
"end": 8085
} | class ____ look up for registrations for
* @return a map with registered MediaType-to-ObjectMapper registrations,
* or empty if in case of no registrations for the given class.
* @since 5.3.4
*/
public @Nullable Map<MimeType, ObjectMapper> getObjectMappersForType(Class<?> clazz) {
for (Map.Entry<Class<?>, Map<MimeType, ObjectMapper>> entry : getObjectMapperRegistrations().entrySet()) {
if (entry.getKey().isAssignableFrom(clazz)) {
return entry.getValue();
}
}
return Collections.emptyMap();
}
protected Map<Class<?>, Map<MimeType, ObjectMapper>> getObjectMapperRegistrations() {
return (this.objectMapperRegistrations != null ? this.objectMapperRegistrations : Collections.emptyMap());
}
/**
* Subclasses should expose this as "decodable" or "encodable" mime types.
*/
protected List<MimeType> getMimeTypes() {
return this.mimeTypes;
}
protected List<MimeType> getMimeTypes(ResolvableType elementType) {
Class<?> elementClass = elementType.toClass();
List<MimeType> result = null;
for (Map.Entry<Class<?>, Map<MimeType, ObjectMapper>> entry : getObjectMapperRegistrations().entrySet()) {
if (entry.getKey().isAssignableFrom(elementClass)) {
result = (result != null ? result : new ArrayList<>(entry.getValue().size()));
result.addAll(entry.getValue().keySet());
}
}
if (!CollectionUtils.isEmpty(result)) {
return result;
}
return (ProblemDetail.class.isAssignableFrom(elementClass) ? getMediaTypesForProblemDetail() : getMimeTypes());
}
/**
* Return the supported media type(s) for {@link ProblemDetail}.
* By default, an empty list, unless overridden in subclasses.
* @since 6.0.5
*/
protected List<MimeType> getMediaTypesForProblemDetail() {
return Collections.emptyList();
}
protected boolean supportsMimeType(@Nullable MimeType mimeType) {
if (mimeType == null) {
return true;
}
for (MimeType supportedMimeType : this.mimeTypes) {
if (supportedMimeType.isCompatibleWith(mimeType)) {
return true;
}
}
return false;
}
/**
* Determine whether to log the given exception coming from a
* {@link ObjectMapper#canDeserialize} / {@link ObjectMapper#canSerialize} check.
* @param type the | to |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/TestAccountConfiguration.java | {
"start": 33040,
"end": 38123
} | class
____.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ASSERTION_PROVIDER_TYPE + accountNameSuffix,
"non.existent.InvalidProvider");
TokenAccessProviderException exception = LambdaTestUtils.intercept(
TokenAccessProviderException.class,
() -> abfsConf.getTokenProvider());
Assertions.assertThat(exception.getMessage())
.describedAs("Should contain error about unable to load OAuth token provider class")
.contains("Unable to load OAuth token provider class");
}
/**
* Test that empty/whitespace custom ClientAssertionProvider config falls back to file-based approach
*/
@Test
public void testWorkloadIdentityTokenProviderWithEmptyCustomProviderConfig() throws Exception {
final String accountName = "account";
final Configuration conf = new Configuration();
final AbfsConfiguration abfsConf = new AbfsConfiguration(conf, accountName);
final String accountNameSuffix = "." + abfsConf.getAccountName();
// Set up OAuth with WorkloadIdentityTokenProvider
abfsConf.set(FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME + accountNameSuffix, AuthType.OAuth.toString());
abfsConf.set(FS_AZURE_ACCOUNT_TOKEN_PROVIDER_TYPE_PROPERTY_NAME + accountNameSuffix,
WorkloadIdentityTokenProvider.class.getName());
// Set required OAuth parameters
abfsConf.set(FS_AZURE_ACCOUNT_OAUTH_MSI_TENANT + accountNameSuffix, TEST_MSI_TENANT);
abfsConf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ID + accountNameSuffix, TEST_CLIENT_ID);
// Set empty custom ClientAssertionProvider - should fallback to file-based
abfsConf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ASSERTION_PROVIDER_TYPE + accountNameSuffix, " ");
AccessTokenProvider tokenProvider = abfsConf.getTokenProvider();
Assertions.assertThat(tokenProvider)
.describedAs("Should create WorkloadIdentityTokenProvider with file-based fallback when provider config is empty")
.isInstanceOf(WorkloadIdentityTokenProvider.class);
// Verify that the empty provider configuration is read but treated as empty
String customProviderType = abfsConf.getPasswordString(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ASSERTION_PROVIDER_TYPE);
Assertions.assertThat(customProviderType)
.describedAs("Empty custom provider config should be present but whitespace-only")
.isEqualTo(" ");
// Verify that when trimmed, it's empty (this is what triggers file-based fallback)
Assertions.assertThat(customProviderType.trim())
.describedAs("Trimmed custom provider config should be empty")
.isEmpty();
}
/**
* Test that configuration precedence works for custom ClientAssertionProvider
* (account-specific vs account-agnostic)
*/
@Test
public void testWorkloadIdentityCustomProviderConfigPrecedence() throws Exception {
final String accountName = "account";
final Configuration conf = new Configuration();
final AbfsConfiguration abfsConf = new AbfsConfiguration(conf, accountName);
final String accountNameSuffix = "." + abfsConf.getAccountName();
// Set up OAuth with WorkloadIdentityTokenProvider
abfsConf.set(FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME + accountNameSuffix, AuthType.OAuth.toString());
abfsConf.set(FS_AZURE_ACCOUNT_TOKEN_PROVIDER_TYPE_PROPERTY_NAME + accountNameSuffix,
WorkloadIdentityTokenProvider.class.getName());
// Set required OAuth parameters
abfsConf.set(FS_AZURE_ACCOUNT_OAUTH_MSI_TENANT + accountNameSuffix, TEST_MSI_TENANT);
abfsConf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ID + accountNameSuffix, TEST_CLIENT_ID);
// Set account-agnostic custom provider (should be overridden by account-specific)
abfsConf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ASSERTION_PROVIDER_TYPE, "some.other.Provider");
// Set account-specific custom provider (should take precedence)
abfsConf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ASSERTION_PROVIDER_TYPE + accountNameSuffix,
TEST_CUSTOM_CLIENT_ASSERTION_PROVIDER);
AccessTokenProvider tokenProvider = abfsConf.getTokenProvider();
Assertions.assertThat(tokenProvider)
.describedAs("Should create WorkloadIdentityTokenProvider with account-specific custom provider taking precedence")
.isInstanceOf(WorkloadIdentityTokenProvider.class);
// Verify that account-specific configuration takes precedence over account-agnostic
String accountSpecificProvider = abfsConf.getPasswordString(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ASSERTION_PROVIDER_TYPE);
Assertions.assertThat(accountSpecificProvider)
.describedAs("Account-specific custom provider should take precedence")
.isEqualTo(TEST_CUSTOM_CLIENT_ASSERTION_PROVIDER);
// Verify that the account-agnostic setting exists but isn't used
String accountAgnosticProvider = abfsConf.getRawConfiguration().get(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ASSERTION_PROVIDER_TYPE);
Assertions.assertThat(accountAgnosticProvider)
.describedAs("Account-agnostic setting should exist but not be used")
.isEqualTo("some.other.Provider");
}
}
| abfsConf |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/issues/TryCatchWithSplitIssueTest.java | {
"start": 2951,
"end": 3226
} | class ____ {
public String dummyException(String payload) {
if (payload.equals("James")) {
throw new IllegalArgumentException("This is a dummy error James!");
}
return "Hi " + payload;
}
}
}
| GenerateError |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/io/ResolverUtil.java | {
"start": 1363,
"end": 2189
} | class ____ that contain classes
* within certain packages, and then to load those classes and check them. By default the ClassLoader returned by
* {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden by calling
* {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()} methods.
* <p>
* General searches are initiated by calling the {@link #find(Test, String)} and supplying a package name and a Test
* instance. This will cause the named package <b>and all sub-packages</b> to be scanned for classes that meet the test.
* There are also utility methods for the common use cases of scanning multiple packages for extensions of particular
* classes, or classes annotated with a specific annotation.
* <p>
* The standard usage pattern for the ResolverUtil | path |
java | alibaba__nacos | config/src/main/java/com/alibaba/nacos/config/server/model/gray/GrayRuleManager.java | {
"start": 1430,
"end": 3999
} | class ____ type and version.
*
* @param type type.
* @param version version.
* @return class.
* @date 2024/3/14
*/
public static Class<?> getClassByTypeAndVersion(String type, String version) {
return GRAY_RULE_MAP.get(type + SPLIT + version);
}
/**
* construct gray rule.
*
* @param configGrayPersistInfo config gray persist info.
* @return gray rule.
* @date 2024/3/14
*/
public static GrayRule constructGrayRule(ConfigGrayPersistInfo configGrayPersistInfo) {
Class<?> classByTypeAndVersion = getClassByTypeAndVersion(configGrayPersistInfo.getType(),
configGrayPersistInfo.getVersion());
if (classByTypeAndVersion == null) {
return null;
}
try {
Constructor<?> declaredConstructor = classByTypeAndVersion.getDeclaredConstructor(String.class, int.class);
declaredConstructor.setAccessible(true);
return (GrayRule) declaredConstructor.newInstance(configGrayPersistInfo.getExpr(),
configGrayPersistInfo.getPriority());
} catch (Exception e) {
throw new RuntimeException(String.format("construct gray rule failed with type[%s], version[%s].",
configGrayPersistInfo.getType(), configGrayPersistInfo.getVersion()), e);
}
}
/**
* construct config gray persist info.
*
* @param grayRule gray rule.
* @return config gray persist info.
* @date 2024/3/14
*/
public static ConfigGrayPersistInfo constructConfigGrayPersistInfo(GrayRule grayRule) {
return new ConfigGrayPersistInfo(grayRule.getType(), grayRule.getVersion(), grayRule.getRawGrayRuleExp(),
grayRule.getPriority());
}
/**
* deserialize config gray persist info.
*
* @param grayRuleRawStringFromDb gray rule raw string from db.
* @return config gray persist info.
* @date 2024/3/14
*/
public static ConfigGrayPersistInfo deserializeConfigGrayPersistInfo(String grayRuleRawStringFromDb) {
return (new Gson()).fromJson(grayRuleRawStringFromDb, ConfigGrayPersistInfo.class);
}
/**
* serialize config gray persist info.
*
* @param configGrayPersistInfo config gray persist info.
* @return serialized string.
* @date 2024/3/14
*/
public static String serializeConfigGrayPersistInfo(ConfigGrayPersistInfo configGrayPersistInfo) {
return (new Gson()).toJson(configGrayPersistInfo);
}
}
| by |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_array_array_2.java | {
"start": 224,
"end": 1131
} | class ____ extends TestCase {
String text = "[[],[],[],[],[], [],[],[],[],[]]";
public void test_read() throws Exception {
JSONReader reader = new JSONReader(new StringReader(text));
reader.startArray();
int count = 0;
while (reader.hasNext()) {
reader.startArray();
reader.endArray();
count++;
}
Assert.assertEquals(10, count);
reader.endArray();
reader.close();
}
public void test_read_1() throws Exception {
JSONReader reader = new JSONReader(new JSONScanner(text));
reader.startArray();
int count = 0;
while (reader.hasNext()) {
reader.startArray();
reader.endArray();
count++;
}
Assert.assertEquals(10, count);
reader.endArray();
reader.close();
}
}
| JSONReaderTest_array_array_2 |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/jdk/CustomMapKeys2454Test.java | {
"start": 738,
"end": 879
} | class ____ {
String id;
public Key2454(String id, boolean bogus) {
this.id = id;
}
}
static | Key2454 |
java | apache__dubbo | dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/ServerTripleMutinyPublisher.java | {
"start": 1175,
"end": 1394
} | class ____<T> extends AbstractTripleMutinyPublisher<T> {
public ServerTripleMutinyPublisher(CallStreamObserver<?> callStreamObserver) {
super.onSubscribe(callStreamObserver);
}
}
| ServerTripleMutinyPublisher |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/inline_association_with_dot/ElementMapperUsingInline.java | {
"start": 723,
"end": 784
} | interface ____ extends ElementMapper {
}
| ElementMapperUsingInline |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/emops/Decorate.java | {
"start": 379,
"end": 908
} | class ____ implements java.io.Serializable {
private int id;
private String name;
private Pet pet;
public Decorate() {
super();
}
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
public int getId() {
return id;
}
public String getName() {
return name;
}
@OneToOne( fetch = FetchType.LAZY )
public Pet getPet() {
return pet;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPet(Pet pet) {
this.pet = pet;
}
}
| Decorate |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/SlowLogFieldProvider.java | {
"start": 632,
"end": 1007
} | interface ____ {
/**
* Create a field provider with index level settings to be able to listen for updates and set initial values
* @param indexSettings settings for the index
*/
SlowLogFields create(IndexSettings indexSettings);
/**
* Create a field provider without index level settings
*/
SlowLogFields create();
}
| SlowLogFieldProvider |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/ConstantFoldingUtil.java | {
"start": 1151,
"end": 1583
} | class ____ {
/**
* Checks whether it contains any function calls which don't support constant folding.
*
* @param node the RexNode to check
* @return true if it contains any unsupported function calls in the specified node.
*/
public static boolean supportsConstantFolding(RexNode node) {
return node.accept(new CanConstantFoldExpressionVisitor());
}
private static | ConstantFoldingUtil |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestGetFileChecksum.java | {
"start": 1275,
"end": 3299
} | class ____ {
private static final int BLOCKSIZE = 1024;
private static final short REPLICATION = 3;
private Configuration conf;
private MiniDFSCluster cluster;
private DistributedFileSystem dfs;
@BeforeEach
public void setUp() throws Exception {
conf = new Configuration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCKSIZE);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(REPLICATION)
.build();
cluster.waitActive();
dfs = cluster.getFileSystem();
}
@AfterEach
public void tearDown() throws Exception {
if (cluster != null) {
cluster.shutdown();
cluster = null;
}
}
public void testGetFileChecksum(final Path foo, final int appendLength)
throws Exception {
final int appendRounds = 16;
FileChecksum[] fc = new FileChecksum[appendRounds + 1];
DFSTestUtil.createFile(dfs, foo, appendLength, REPLICATION, 0L);
fc[0] = dfs.getFileChecksum(foo);
for (int i = 0; i < appendRounds; i++) {
DFSTestUtil.appendFile(dfs, foo, appendLength);
fc[i + 1] = dfs.getFileChecksum(foo);
}
for (int i = 0; i < appendRounds + 1; i++) {
FileChecksum checksum = dfs.getFileChecksum(foo, appendLength * (i+1));
assertTrue(checksum.equals(fc[i]));
}
}
@Test
public void testGetFileChecksumForBlocksUnderConstruction() {
try {
FSDataOutputStream file = dfs.create(new Path("/testFile"));
file.write("Performance Testing".getBytes());
dfs.getFileChecksum(new Path("/testFile"));
fail("getFileChecksum should fail for files "
+ "with blocks under construction");
} catch (IOException ie) {
assertTrue(ie.getMessage()
.contains("Fail to get checksum, since file /testFile "
+ "is under construction."));
}
}
@Test
public void testGetFileChecksum() throws Exception {
testGetFileChecksum(new Path("/foo"), BLOCKSIZE / 4);
testGetFileChecksum(new Path("/bar"), BLOCKSIZE / 4 - 1);
}
}
| TestGetFileChecksum |
java | apache__avro | lang/java/avro/src/test/java/org/apache/avro/data/TestTimeConversions.java | {
"start": 1608,
"end": 11679
} | class ____ {
public static Schema DATE_SCHEMA;
public static Schema TIME_MILLIS_SCHEMA;
public static Schema TIME_MICROS_SCHEMA;
public static Schema TIMESTAMP_MILLIS_SCHEMA;
public static Schema TIMESTAMP_MICROS_SCHEMA;
@BeforeAll
public static void createSchemas() {
TestTimeConversions.DATE_SCHEMA = LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT));
TestTimeConversions.TIME_MILLIS_SCHEMA = LogicalTypes.timeMillis().addToSchema(Schema.create(Schema.Type.INT));
TestTimeConversions.TIME_MICROS_SCHEMA = LogicalTypes.timeMicros().addToSchema(Schema.create(Schema.Type.LONG));
TestTimeConversions.TIMESTAMP_MILLIS_SCHEMA = LogicalTypes.timestampMillis()
.addToSchema(Schema.create(Schema.Type.LONG));
TestTimeConversions.TIMESTAMP_MICROS_SCHEMA = LogicalTypes.timestampMicros()
.addToSchema(Schema.create(Schema.Type.LONG));
}
@Test
void dateConversion() throws Exception {
DateConversion conversion = new DateConversion();
LocalDate Jan_6_1970 = LocalDate.of(1970, 1, 6); // 5
LocalDate Jan_1_1970 = LocalDate.of(1970, 1, 1); // 0
LocalDate Dec_27_1969 = LocalDate.of(1969, 12, 27); // -5
assertEquals(5, (int) conversion.toInt(Jan_6_1970, DATE_SCHEMA, LogicalTypes.date()), "6 Jan 1970 should be 5");
assertEquals(0, (int) conversion.toInt(Jan_1_1970, DATE_SCHEMA, LogicalTypes.date()), "1 Jan 1970 should be 0");
assertEquals(-5, (int) conversion.toInt(Dec_27_1969, DATE_SCHEMA, LogicalTypes.date()), "27 Dec 1969 should be -5");
assertEquals(conversion.fromInt(5, DATE_SCHEMA, LogicalTypes.date()), Jan_6_1970, "6 Jan 1970 should be 5");
assertEquals(conversion.fromInt(0, DATE_SCHEMA, LogicalTypes.date()), Jan_1_1970, "1 Jan 1970 should be 0");
assertEquals(conversion.fromInt(-5, DATE_SCHEMA, LogicalTypes.date()), Dec_27_1969, "27 Dec 1969 should be -5");
}
@Test
void timeMillisConversion() {
TimeMillisConversion conversion = new TimeMillisConversion();
LocalTime oneAM = LocalTime.of(1, 0);
LocalTime afternoon = LocalTime.of(15, 14, 15, 926_000_000);
int afternoonMillis = ((15 * 60 + 14) * 60 + 15) * 1000 + 926;
assertEquals(0, (int) conversion.toInt(LocalTime.MIDNIGHT, TIME_MILLIS_SCHEMA, LogicalTypes.timeMillis()),
"Midnight should be 0");
assertEquals(3_600_000, (int) conversion.toInt(oneAM, TIME_MILLIS_SCHEMA, LogicalTypes.timeMillis()),
"01:00 should be 3,600,000");
assertEquals(afternoonMillis, (int) conversion.toInt(afternoon, TIME_MILLIS_SCHEMA, LogicalTypes.timeMillis()),
"15:14:15.926 should be " + afternoonMillis);
assertEquals(LocalTime.MIDNIGHT, conversion.fromInt(0, TIME_MILLIS_SCHEMA, LogicalTypes.timeMillis()),
"Midnight should be 0");
assertEquals(oneAM, conversion.fromInt(3600000, TIME_MILLIS_SCHEMA, LogicalTypes.timeMillis()),
"01:00 should be 3,600,000");
assertEquals(afternoon, conversion.fromInt(afternoonMillis, TIME_MILLIS_SCHEMA, LogicalTypes.timeMillis()),
"15:14:15.926 should be " + afternoonMillis);
}
@Test
void timeMicrosConversion() throws Exception {
TimeMicrosConversion conversion = new TimeMicrosConversion();
LocalTime oneAM = LocalTime.of(1, 0);
LocalTime afternoon = LocalTime.of(15, 14, 15, 926_551_000);
long afternoonMicros = ((long) (15 * 60 + 14) * 60 + 15) * 1_000_000 + 926_551;
assertEquals(LocalTime.MIDNIGHT, conversion.fromLong(0L, TIME_MICROS_SCHEMA, LogicalTypes.timeMicros()),
"Midnight should be 0");
assertEquals(oneAM, conversion.fromLong(3_600_000_000L, TIME_MICROS_SCHEMA, LogicalTypes.timeMicros()),
"01:00 should be 3,600,000,000");
assertEquals(afternoon, conversion.fromLong(afternoonMicros, TIME_MICROS_SCHEMA, LogicalTypes.timeMicros()),
"15:14:15.926551 should be " + afternoonMicros);
assertEquals(0, (long) conversion.toLong(LocalTime.MIDNIGHT, TIME_MICROS_SCHEMA, LogicalTypes.timeMicros()),
"Midnight should be 0");
assertEquals(3_600_000_000L, (long) conversion.toLong(oneAM, TIME_MICROS_SCHEMA, LogicalTypes.timeMicros()),
"01:00 should be 3,600,000,000");
assertEquals(afternoonMicros, (long) conversion.toLong(afternoon, TIME_MICROS_SCHEMA, LogicalTypes.timeMicros()),
"15:14:15.926551 should be " + afternoonMicros);
}
@Test
void timestampMillisConversion() throws Exception {
TimestampMillisConversion conversion = new TimestampMillisConversion();
long nowInstant = Instant.now().toEpochMilli(); // ms precision
// round trip
Instant now = conversion.fromLong(nowInstant, TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis());
long roundTrip = conversion.toLong(now, TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis());
assertEquals(nowInstant, roundTrip, "Round-trip conversion should work");
long May_28_2015_21_46_53_221_instant = 1432849613221L;
Instant May_28_2015_21_46_53_221 = ZonedDateTime.of(2015, 5, 28, 21, 46, 53, 221_000_000, ZoneOffset.UTC)
.toInstant();
// known dates from https://www.epochconverter.com/
// > Epoch
assertEquals(May_28_2015_21_46_53_221,
conversion.fromLong(May_28_2015_21_46_53_221_instant, TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis()),
"Known date should be correct");
assertEquals(May_28_2015_21_46_53_221_instant,
(long) conversion.toLong(May_28_2015_21_46_53_221, TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis()),
"Known date should be correct");
// Epoch
assertEquals(Instant.EPOCH, conversion.fromLong(0L, TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis()),
"1970-01-01 should be 0");
assertEquals(0L, (long) conversion.toLong(ZonedDateTime.ofInstant(Instant.EPOCH, ZoneOffset.UTC).toInstant(),
TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis()), "1970-01-01 should be 0");
// < Epoch
long Jul_01_1969_12_00_00_123_instant = -15854400000L + 123;
Instant Jul_01_1969_12_00_00_123 = ZonedDateTime.of(1969, 7, 1, 12, 0, 0, 123_000_000, ZoneOffset.UTC).toInstant();
assertEquals(Jul_01_1969_12_00_00_123,
conversion.fromLong(Jul_01_1969_12_00_00_123_instant, TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis()),
"Pre 1970 date should be correct");
assertEquals(Jul_01_1969_12_00_00_123_instant,
(long) conversion.toLong(Jul_01_1969_12_00_00_123, TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis()),
"Pre 1970 date should be correct");
}
@Test
void timestampMicrosConversion() throws Exception {
TimestampMicrosConversion conversion = new TimestampMicrosConversion();
// known dates from https://www.epochconverter.com/
// > Epoch
long May_28_2015_21_46_53_221_843_instant = 1432849613221L * 1000 + 843;
Instant May_28_2015_21_46_53_221_843 = ZonedDateTime.of(2015, 5, 28, 21, 46, 53, 221_843_000, ZoneOffset.UTC)
.toInstant();
assertEquals(May_28_2015_21_46_53_221_843, conversion.fromLong(May_28_2015_21_46_53_221_843_instant,
TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()), "Known date should be correct");
assertEquals(May_28_2015_21_46_53_221_843_instant,
(long) conversion.toLong(May_28_2015_21_46_53_221_843, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMillis()),
"Known date should be correct");
// Epoch
assertEquals(Instant.EPOCH, conversion.fromLong(0L, TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis()),
"1970-01-01 should be 0");
assertEquals(0L, (long) conversion.toLong(ZonedDateTime.ofInstant(Instant.EPOCH, ZoneOffset.UTC).toInstant(),
TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis()), "1970-01-01 should be 0");
// < Epoch
long Jul_01_1969_12_00_00_000_123_instant = -15854400000L * 1000 + 123;
Instant Jul_01_1969_12_00_00_000_123 = ZonedDateTime.of(1969, 7, 1, 12, 0, 0, 123_000, ZoneOffset.UTC).toInstant();
assertEquals(Jul_01_1969_12_00_00_000_123, conversion.fromLong(Jul_01_1969_12_00_00_000_123_instant,
TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis()), "Pre 1970 date should be correct");
assertEquals(Jul_01_1969_12_00_00_000_123_instant,
(long) conversion.toLong(Jul_01_1969_12_00_00_000_123, TIMESTAMP_MILLIS_SCHEMA, LogicalTypes.timestampMillis()),
"Pre 1970 date should be correct");
}
@Test
void dynamicSchemaWithDateConversion() throws ClassNotFoundException {
Schema schema = getReflectedSchemaByName("java.time.LocalDate", new TimeConversions.DateConversion());
assertEquals(DATE_SCHEMA, schema, "Reflected schema should be logicalType date");
}
@Test
void dynamicSchemaWithTimeConversion() throws ClassNotFoundException {
Schema schema = getReflectedSchemaByName("java.time.LocalTime", new TimeConversions.TimeMillisConversion());
assertEquals(TIME_MILLIS_SCHEMA, schema, "Reflected schema should be logicalType timeMillis");
}
@Test
void dynamicSchemaWithTimeMicrosConversion() throws ClassNotFoundException {
Schema schema = getReflectedSchemaByName("java.time.LocalTime", new TimeConversions.TimeMicrosConversion());
assertEquals(TIME_MICROS_SCHEMA, schema, "Reflected schema should be logicalType timeMicros");
}
@Test
void dynamicSchemaWithDateTimeConversion() throws ClassNotFoundException {
Schema schema = getReflectedSchemaByName("java.time.Instant", new TimeConversions.TimestampMillisConversion());
assertEquals(TIMESTAMP_MILLIS_SCHEMA, schema, "Reflected schema should be logicalType timestampMillis");
}
@Test
void dynamicSchemaWithDateTimeMicrosConversion() throws ClassNotFoundException {
Schema schema = getReflectedSchemaByName("java.time.Instant", new TimeConversions.TimestampMicrosConversion());
assertEquals(TIMESTAMP_MICROS_SCHEMA, schema, "Reflected schema should be logicalType timestampMicros");
}
private Schema getReflectedSchemaByName(String className, Conversion<?> conversion) throws ClassNotFoundException {
// one argument: a fully qualified | TestTimeConversions |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/issues/SedaFileIdempotentNoTimeoutIssueTest.java | {
"start": 943,
"end": 1610
} | class ____ extends SedaFileIdempotentIssueTest {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
onException(RuntimeException.class).process(new ShutDown());
from(fileUri("inbox?idempotent=true&noop=true&idempotentRepository=#repo&initialDelay=0&delay=10"))
.to("log:begin").to(ExchangePattern.InOut, "seda:process?timeout=-1");
from("seda:process").throwException(new RuntimeException("Testing with exception"));
}
};
}
}
| SedaFileIdempotentNoTimeoutIssueTest |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/targetclass/mixed/PostConstructOnTargetClassAndOutsideAndSuperclassesTest.java | {
"start": 1965,
"end": 2299
} | class ____ {
@PostConstruct
void superPostConstruct(InvocationContext ctx) throws Exception {
MyBean.invocations.add(MyInterceptorSuperclass.class.getSimpleName());
ctx.proceed();
}
}
@MyInterceptorBinding
@Interceptor
@Priority(1)
public static | MyInterceptorSuperclass |
java | spring-projects__spring-framework | spring-jms/src/test/java/org/springframework/jms/config/MethodJmsListenerEndpointTests.java | {
"start": 20058,
"end": 24752
} | class ____ {
private final Map<String, Boolean> invocations = new HashMap<>();
public void resolveMessageAndSession(jakarta.jms.Message message, Session session) {
this.invocations.put("resolveMessageAndSession", true);
assertThat(message).as("Message not injected").isNotNull();
assertThat(session).as("Session not injected").isNotNull();
}
public void resolveGenericMessage(Message<String> message) {
this.invocations.put("resolveGenericMessage", true);
assertThat(message).as("Generic message not injected").isNotNull();
assertThat(message.getPayload()).as("Wrong message payload").isEqualTo("test");
}
public void resolveHeaderAndPayload(@Payload String content, @Header int myCounter) {
this.invocations.put("resolveHeaderAndPayload", true);
assertThat(content).as("Wrong @Payload resolution").isEqualTo("my payload");
assertThat(myCounter).as("Wrong @Header resolution").isEqualTo(55);
}
public void resolveCustomHeaderNameAndPayload(@Payload String content, @Header("myCounter") int counter) {
this.invocations.put("resolveCustomHeaderNameAndPayload", true);
assertThat(content).as("Wrong @Payload resolution").isEqualTo("my payload");
assertThat(counter).as("Wrong @Header resolution").isEqualTo(24);
}
public void resolveCustomHeaderNameAndPayloadWithHeaderNameSet(@Payload String content, @Header(name = "myCounter") int counter) {
this.invocations.put("resolveCustomHeaderNameAndPayloadWithHeaderNameSet", true);
assertThat(content).as("Wrong @Payload resolution").isEqualTo("my payload");
assertThat(counter).as("Wrong @Header resolution").isEqualTo(24);
}
public void resolveHeaders(String content, @Headers Map<String, Object> headers) {
this.invocations.put("resolveHeaders", true);
assertThat(content).as("Wrong payload resolution").isEqualTo("my payload");
assertThat(headers).as("headers not injected").isNotNull();
assertThat(headers.get(JmsHeaders.MESSAGE_ID)).as("Missing JMS message id header").isEqualTo("abcd-1234");
assertThat(headers.get("customInt")).as("Missing custom header").isEqualTo(1234);
}
public void resolveMessageHeaders(MessageHeaders headers) {
this.invocations.put("resolveMessageHeaders", true);
assertThat(headers).as("MessageHeaders not injected").isNotNull();
assertThat(headers.get(JmsHeaders.TYPE)).as("Missing JMS message type header").isEqualTo("myMessageType");
assertThat((long) headers.get("customLong")).as("Missing custom header").isEqualTo(4567);
}
public void resolveJmsMessageHeaderAccessor(JmsMessageHeaderAccessor headers) {
this.invocations.put("resolveJmsMessageHeaderAccessor", true);
assertThat(headers).as("MessageHeaders not injected").isNotNull();
assertThat(headers.getPriority()).as("Missing JMS message priority header").isEqualTo(Integer.valueOf(9));
assertThat(headers.getHeader("customBoolean")).as("Missing custom header").asInstanceOf(BOOLEAN).isTrue();
}
public void resolveObjectPayload(MyBean bean) {
this.invocations.put("resolveObjectPayload", true);
assertThat(bean).as("Object payload not injected").isNotNull();
assertThat(bean.name).as("Wrong content for payload").isEqualTo("myBean name");
}
public void resolveConvertedPayload(Integer counter) {
this.invocations.put("resolveConvertedPayload", true);
assertThat(counter).as("Payload not injected").isNotNull();
assertThat(counter).as("Wrong content for payload").isEqualTo(Integer.valueOf(33));
}
public String processAndReply(@Payload String content) {
this.invocations.put("processAndReply", true);
return content;
}
@SendTo("replyDestination")
public String processAndReplyWithSendTo(String content) {
this.invocations.put("processAndReplyWithSendTo", true);
return content;
}
public String processAndReplyWithDefaultSendTo(String content) {
this.invocations.put("processAndReplyWithDefaultSendTo", true);
return content;
}
@SendTo("")
public String emptySendTo(String content) {
this.invocations.put("emptySendTo", true);
return content;
}
@SendTo({"firstDestination", "secondDestination"})
public String invalidSendTo(String content) {
this.invocations.put("invalidSendTo", true);
return content;
}
public void validatePayload(@Validated String payload) {
this.invocations.put("validatePayload", true);
}
public void invalidPayloadType(@Payload Integer payload) {
throw new IllegalStateException("Should never be called.");
}
public void invalidMessagePayloadType(Message<Integer> message) {
throw new IllegalStateException("Should never be called.");
}
}
@SuppressWarnings("serial")
static | JmsEndpointSampleBean |
java | quarkusio__quarkus | integration-tests/observability-lgtm-fixedports/src/main/java/io/quarkus/observability/example/SimpleEndpoint.java | {
"start": 482,
"end": 1253
} | class ____ {
private static final Logger log = Logger.getLogger(SimpleEndpoint.class);
@Inject
MeterRegistry registry;
Random random = new SecureRandom();
double[] arr = new double[1];
@PostConstruct
public void start() {
String key = System.getProperty("tag-key", "test");
Gauge.builder("xvalue", arr, a -> arr[0])
.baseUnit("X")
.description("Some random x")
.tag(key, "x")
.register(registry);
}
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/poke")
public String poke(@QueryParam("f") int f) {
log.infof("Poke %s", f);
double x = random.nextDouble() * f;
arr[0] = x;
return "poke:" + x;
}
}
| SimpleEndpoint |
java | micronaut-projects__micronaut-core | inject-java/src/main/java/io/micronaut/annotation/processing/AggregatingTypeElementVisitorProcessor.java | {
"start": 1144,
"end": 2454
} | class ____ extends TypeElementVisitorProcessor {
@Override
protected String getIncrementalProcessorType() {
return GRADLE_PROCESSING_AGGREGATING;
}
@Override
public Set<String> getSupportedAnnotationTypes() {
if (!hasVisitors()) {
return Collections.emptySet();
}
if (isIncremental(processingEnv)) {
List<LoadedVisitor> loadedVisitors = getLoadedVisitors();
var annotationNames = new HashSet<String>();
// try and narrow the annotations to only the ones interesting to the visitors
// if a visitor is interested in Object than fall back to all
for (LoadedVisitor loadedVisitor : loadedVisitors) {
TypeElementVisitor<?, ?> visitor = loadedVisitor.getVisitor();
Set<String> supportedAnnotationNames = visitor.getSupportedAnnotationNames();
if (supportedAnnotationNames.contains("*")) {
return super.getSupportedAnnotationTypes();
} else {
annotationNames.addAll(supportedAnnotationNames);
}
}
return annotationNames;
} else {
return super.getSupportedAnnotationTypes();
}
}
}
| AggregatingTypeElementVisitorProcessor |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/Farm.java | {
"start": 344,
"end": 796
} | class ____ {
@Id
private Integer id;
@Basic
private String name;
@Embedded
@Convert(
attributeName = "city",
converter = ToEntityAttributeThrowRuntimeExceptionConverter.class)
private Address address;
Farm() {
}
public Farm(Integer id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public Integer getId() {
return id;
}
public Address getAddress() {
return address;
}
}
| Farm |
java | apache__maven | its/core-it-support/core-it-plugins/maven-it-plugin-configuration/src/main/java/org/apache/maven/plugin/coreit/TouchMojo.java | {
"start": 1297,
"end": 2086
} | class ____ extends AbstractMojo {
@Parameter(defaultValue = "${project.build.directory}")
private File outputDirectory;
@Parameter(alias = "validParameterAlias")
private String validParameter;
public void execute() throws MojoExecutionException {
getLog().info("[MAVEN-CORE-IT-LOG] Using output directory " + outputDirectory);
touch(outputDirectory, "touch.txt");
}
static void touch(File dir, String file) throws MojoExecutionException {
try {
if (!dir.exists()) {
dir.mkdirs();
}
File touch = new File(dir, file);
touch.createNewFile();
} catch (IOException e) {
throw new MojoExecutionException("Error touching file", e);
}
}
}
| TouchMojo |
java | apache__dubbo | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterWrapper.java | {
"start": 1186,
"end": 1649
} | class ____ implements Cluster {
private final Cluster cluster;
public ScopeClusterWrapper(Cluster cluster) {
this.cluster = cluster;
}
@Override
public <T> Invoker<T> join(Directory<T> directory, boolean buildFilterChain) throws RpcException {
return new ScopeClusterInvoker<>(directory, this.cluster.join(directory, buildFilterChain));
}
public Cluster getCluster() {
return cluster;
}
}
| ScopeClusterWrapper |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/UriAssertBaseTest.java | {
"start": 763,
"end": 818
} | class ____ {@link UriAssert} tests.
*/
public abstract | for |
java | apache__camel | components/camel-ibm/camel-ibm-secrets-manager/src/generated/java/org/apache/camel/component/ibm/secrets/manager/IBMSecretsManagerComponentConfigurer.java | {
"start": 746,
"end": 2367
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
IBMSecretsManagerComponent target = (IBMSecretsManagerComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
IBMSecretsManagerComponent target = (IBMSecretsManagerComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
default: return null;
}
}
}
| IBMSecretsManagerComponentConfigurer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.