language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__maven
compat/maven-builder-support/src/main/java/org/apache/maven/building/UrlSource.java
{ "start": 1119, "end": 2436 }
class ____ implements Source { private final URL url; private final int hashCode; /** * Creates a new source backed by the specified URL. * * @param url The file, must not be {@code null}. */ public UrlSource(URL url) { this.url = Objects.requireNonNull(url, "url cannot be null"); this.hashCode = Objects.hashCode(url); } @Override public InputStream getInputStream() throws IOException { return url.openStream(); } @Override public String getLocation() { return url.toString(); } /** * Gets the URL of this source. * * @return The underlying URL, never {@code null}. */ public URL getUrl() { return url; } @Override public String toString() { return getLocation(); } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!UrlSource.class.equals(obj.getClass())) { return false; } UrlSource other = (UrlSource) obj; return Objects.equals(url.toExternalForm(), other.url.toExternalForm()); } }
UrlSource
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/util/JandexUtilTest.java
{ "start": 8496, "end": 8580 }
class ____ extends AbstractSingle<Integer> { } public static
AbstractSingleImpl
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocator.java
{ "start": 59489, "end": 85884 }
class ____ implements Comparator<ShardRouting> { /** * This is the threshold over which we consider shards to have a "high" write load represented * as a ratio of the maximum write-load present on the node. * <p> * We prefer to move shards that have a write-load close to <b>this value</b> x {@link #maxWriteLoadOnNode}. */ public static final double THRESHOLD_RATIO = 0.5; private static final double MISSING_WRITE_LOAD = -1; private final Map<ShardId, Double> shardWriteLoads; private final double maxWriteLoadOnNode; private final double threshold; private final String nodeId; public PrioritiseByShardWriteLoadComparator(ClusterInfo clusterInfo, RoutingNode routingNode) { shardWriteLoads = clusterInfo.getShardWriteLoads(); double maxWriteLoadOnNode = MISSING_WRITE_LOAD; for (ShardRouting shardRouting : routingNode) { maxWriteLoadOnNode = Math.max( maxWriteLoadOnNode, shardWriteLoads.getOrDefault(shardRouting.shardId(), MISSING_WRITE_LOAD) ); } this.maxWriteLoadOnNode = maxWriteLoadOnNode; threshold = maxWriteLoadOnNode * THRESHOLD_RATIO; nodeId = routingNode.nodeId(); } @Override public int compare(ShardRouting lhs, ShardRouting rhs) { assert nodeId.equals(lhs.currentNodeId()) && nodeId.equals(rhs.currentNodeId()) : this.getClass().getSimpleName() + " is node-specific. comparator=" + nodeId + ", lhs=" + lhs.currentNodeId() + ", rhs=" + rhs.currentNodeId(); // If we have no shard write-load data, shortcut if (maxWriteLoadOnNode == MISSING_WRITE_LOAD) { return 0; } final double lhsWriteLoad = shardWriteLoads.getOrDefault(lhs.shardId(), MISSING_WRITE_LOAD); final double rhsWriteLoad = shardWriteLoads.getOrDefault(rhs.shardId(), MISSING_WRITE_LOAD); // prefer any known write-load over any unknown write-load final var rhsIsMissing = rhsWriteLoad == MISSING_WRITE_LOAD; final var lhsIsMissing = lhsWriteLoad == MISSING_WRITE_LOAD; if (rhsIsMissing && lhsIsMissing) { return 0; } if (rhsIsMissing ^ lhsIsMissing) { return lhsIsMissing ? 1 : -1; } if (lhsWriteLoad < maxWriteLoadOnNode && rhsWriteLoad < maxWriteLoadOnNode) { final var lhsOverThreshold = lhsWriteLoad >= threshold; final var rhsOverThreshold = rhsWriteLoad >= threshold; if (lhsOverThreshold && rhsOverThreshold) { // Both values between threshold and maximum, prefer lowest return Double.compare(lhsWriteLoad, rhsWriteLoad); } else if (lhsOverThreshold) { // lhs between threshold and maximum, rhs below threshold, prefer lhs return -1; } else if (rhsOverThreshold) { // lhs below threshold, rhs between threshold and maximum, prefer rhs return 1; } // Both values below the threshold, prefer highest return Double.compare(rhsWriteLoad, lhsWriteLoad); } // prefer the non-max write load if there is one return Double.compare(lhsWriteLoad, rhsWriteLoad); } } private Decision decideCanAllocate(ShardRouting shardRouting, RoutingNode target) { // don't use canRebalance as we want hard filtering rules to apply. See #17698 return allocation.deciders().canAllocate(shardRouting, target, allocation); } private Decision decideCanForceAllocateForVacate(ShardRouting shardRouting, RoutingNode target) { return allocation.deciders().canForceAllocateDuringReplace(shardRouting, target, allocation); } /** * Builds the internal model from all shards in the given * {@link Iterable}. All shards in the {@link Iterable} must be assigned * to a node. This method will skip shards in the state * {@link ShardRoutingState#RELOCATING} since each relocating shard has * a shadow shard in the state {@link ShardRoutingState#INITIALIZING} * on the target node which we respect during the allocation / balancing * process. In short, this method recreates the status-quo in the cluster. */ private Map<String, ModelNode> buildModelFromAssigned(boolean diskUsageIgnored) { Map<String, ModelNode> nodes = Maps.newMapWithExpectedSize(routingNodes.size()); for (RoutingNode rn : routingNodes) { ModelNode node = new ModelNode(writeLoadForecaster, metadata, allocation.clusterInfo(), rn, diskUsageIgnored); nodes.put(rn.nodeId(), node); for (ShardRouting shard : rn) { assert rn.nodeId().equals(shard.currentNodeId()); /* we skip relocating shards here since we expect an initializing shard with the same id coming in */ if (shard.state() != RELOCATING) { node.addShard(projectIndex(shard), shard); if (logger.isTraceEnabled()) { logger.trace("Assigned shard [{}] to node [{}]", shard, node.getNodeId()); } } } } return nodes; } /** * Allocates all given shards on the minimal eligible node for the shards index * with respect to the weight function. All given shards must be unassigned. */ private boolean allocateUnassigned() { RoutingNodes.UnassignedShards unassigned = routingNodes.unassigned(); assert nodes.isEmpty() == false; if (logger.isTraceEnabled()) { logger.trace("Start allocating unassigned shards"); } if (unassigned.isEmpty()) { return false; } /* * TODO: We could be smarter here and group the shards by index and then * use the sorter to save some iterations. */ final PriorityComparator secondaryComparator = PriorityComparator.getAllocationComparator(allocation); final Comparator<ShardRouting> comparator = (o1, o2) -> { if (o1.primary() ^ o2.primary()) { return o1.primary() ? -1 : 1; } if (o1.getIndexName().compareTo(o2.getIndexName()) == 0) { return o1.getId() - o2.getId(); } // this comparator is more expensive than all the others up there // that's why it's added last even though it could be easier to read // if we'd apply it earlier. this comparator will only differentiate across // indices all shards of the same index is treated equally. final int secondary = secondaryComparator.compare(o1, o2); assert secondary != 0 : "Index names are equal, should be returned early."; return secondary; }; /* * we use 2 arrays and move replicas to the second array once we allocated an identical * replica in the current iteration to make sure all indices get allocated in the same manner. * The arrays are sorted by primaries first and then by index and shard ID so a 2 indices with * 2 replica and 1 shard would look like: * [(0,P,IDX1), (0,P,IDX2), (0,R,IDX1), (0,R,IDX1), (0,R,IDX2), (0,R,IDX2)] * if we allocate for instance (0, R, IDX1) we move the second replica to the secondary array and proceed with * the next replica. If we could not find a node to allocate (0,R,IDX1) we move all it's replicas to ignoreUnassigned. */ ShardRouting[] primary = unassigned.drain(); ShardRouting[] secondary = new ShardRouting[primary.length]; int secondaryLength = 0; int primaryLength = primary.length; ArrayUtil.timSort(primary, comparator); boolean shardAssignmentChanged = false; do { for (int i = 0; i < primaryLength; i++) { ShardRouting shard = primary[i]; final ProjectIndex index = projectIndex(shard); final AllocateUnassignedDecision allocationDecision = decideAllocateUnassigned(index, shard); assert allocationDecision.isDecisionTaken() : "decision not taken for unassigned shard [" + shard + "]"; // If we see a THROTTLE decision, it's either: // 1. Not simulating // 2. Or, there is shard assigned before this one assert allocation.isSimulating() == false || allocationDecision.getAllocationStatus() != AllocationStatus.DECIDERS_THROTTLED || shardAssignmentChanged : "unexpected THROTTLE decision (isSimulating=" + allocation.isSimulating() + ") with no prior assignment when allocating unassigned shard [" + shard + "]"; final String assignedNodeId = allocationDecision.getTargetNode() != null ? allocationDecision.getTargetNode().getId() : null; final ModelNode minNode = assignedNodeId != null ? nodes.get(assignedNodeId) : null; if (allocationDecision.getAllocationDecision() == AllocationDecision.YES) { if (logger.isTraceEnabled()) { logger.trace("Assigned shard [{}] to [{}]", shard, minNode.getNodeId()); } final long shardSize = getExpectedShardSize(shard, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE, allocation); shard = routingNodes.initializeShard(shard, minNode.getNodeId(), null, shardSize, allocation.changes()); shardAssignmentChanged = true; minNode.addShard(index, shard); if (shard.primary() == false) { // copy over the same replica shards to the secondary array so they will get allocated // in a subsequent iteration, allowing replicas of other shards to be allocated first while (i < primaryLength - 1 && comparator.compare(primary[i], primary[i + 1]) == 0) { secondary[secondaryLength++] = primary[++i]; } } } else { // did *not* receive a YES decision if (logger.isTraceEnabled()) { logger.trace( "No eligible node found to assign shard [{}] allocation_status [{}]", shard, allocationDecision.getAllocationStatus() ); } if (minNode != null) { // throttle decision scenario assert allocationDecision.getAllocationStatus() == AllocationStatus.DECIDERS_THROTTLED; final long shardSize = getExpectedShardSize(shard, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE, allocation); minNode.addShard(projectIndex(shard), shard.initialize(minNode.getNodeId(), null, shardSize)); } else { if (logger.isTraceEnabled()) { logger.trace("No Node found to assign shard [{}]", shard); } } unassigned.ignoreShard(shard, allocationDecision.getAllocationStatus(), allocation.changes()); if (shard.primary() == false) { // we could not allocate it and we are a replica - check if we can ignore the other replicas while (i < primaryLength - 1 && comparator.compare(primary[i], primary[i + 1]) == 0) { unassigned.ignoreShard(primary[++i], allocationDecision.getAllocationStatus(), allocation.changes()); } } } } primaryLength = secondaryLength; ShardRouting[] tmp = primary; primary = secondary; secondary = tmp; secondaryLength = 0; } while (primaryLength > 0); // clear everything we have either added it or moved to ignoreUnassigned return shardAssignmentChanged; } private ProjectIndex projectIndex(ShardRouting shardRouting) { return new ProjectIndex(allocation, shardRouting); } /** * Make a decision for allocating an unassigned shard. This method returns a two values in a tuple: the * first value is the {@link Decision} taken to allocate the unassigned shard, the second value is the * {@link ModelNode} representing the node that the shard should be assigned to. If the decision returned * is of type {@link Type#NO}, then the assigned node will be null. */ private AllocateUnassignedDecision decideAllocateUnassigned(final ProjectIndex index, final ShardRouting shard) { WeightFunction weightFunction = balancingWeights.weightFunctionForShard(shard); index.assertMatch(shard); if (shard.assignedToNode()) { // we only make decisions for unassigned shards here return AllocateUnassignedDecision.NOT_TAKEN; } final boolean explain = allocation.debugDecision(); Decision shardLevelDecision = allocation.deciders().canAllocate(shard, allocation); if (shardLevelDecision.type() == Type.NO && explain == false) { // NO decision for allocating the shard, irrespective of any particular node, so exit early return AllocateUnassignedDecision.no(AllocationStatus.DECIDERS_NO, null); } /* find an node with minimal weight we can allocate on*/ float minWeight = Float.POSITIVE_INFINITY; ModelNode minNode = null; Decision decision = null; /* Don't iterate over an identity hashset here the * iteration order is different for each run and makes testing hard */ Map<String, NodeAllocationResult> nodeExplanationMap = explain ? new HashMap<>() : null; List<Tuple<String, Float>> nodeWeights = explain ? new ArrayList<>() : null; for (ModelNode node : nodes.values()) { if (node.containsShard(index, shard) && explain == false) { // decision is NO without needing to check anything further, so short circuit continue; } // weight of this index currently on the node float currentWeight = weightFunction.calculateNodeWeightWithIndex(this, node, index); Decision currentDecision = allocation.deciders().canAllocate(shard, node.getRoutingNode(), allocation); if (explain) { nodeExplanationMap.put(node.getNodeId(), new NodeAllocationResult(node.getRoutingNode().node(), currentDecision, 0)); nodeWeights.add(Tuple.tuple(node.getNodeId(), currentWeight)); } if (currentDecision.type() == Type.YES || currentDecision.type() == Type.THROTTLE || currentDecision.type() == Type.NOT_PREFERRED) { final boolean updateMinNode; if (currentWeight == minWeight) { /* we have an equal weight tie breaking: * 1. if one decision is YES prefer it * 2. prefer the node that holds the primary for this index with the next id in the ring ie. * for the 3 shards 2 replica case we try to build up: * 1 2 0 * 2 0 1 * 0 1 2 * such that if we need to tie-break we try to prefer the node holding a shard with the minimal id greater * than the id of the shard we need to assign. This works find when new indices are created since * primaries are added first and we only add one shard set a time in this algorithm. */ if (currentDecision.type() == decision.type()) { final int repId = shard.id(); final int nodeHigh = node.highestPrimary(index); final int minNodeHigh = minNode.highestPrimary(index); updateMinNode = ((((nodeHigh > repId && minNodeHigh > repId) || (nodeHigh < repId && minNodeHigh < repId)) && (nodeHigh < minNodeHigh)) || (nodeHigh > repId && minNodeHigh < repId)); } else { // always prefer a YES, prefer anything over a NOT_PREFERRED updateMinNode = currentDecision.type() == Type.YES || decision.type() == Type.NOT_PREFERRED; } } else { updateMinNode = preferNewDecisionOverExisting(currentDecision, currentWeight, decision, minWeight); } if (updateMinNode) { minNode = node; minWeight = currentWeight; decision = currentDecision; } } } if (decision == null) { // decision was not set and a node was not assigned, so treat it as a NO decision decision = Decision.NO; } List<NodeAllocationResult> nodeDecisions = null; if (explain) { nodeDecisions = new ArrayList<>(); // fill in the correct weight ranking, once we've been through all nodes nodeWeights.sort((nodeWeight1, nodeWeight2) -> Float.compare(nodeWeight1.v2(), nodeWeight2.v2())); int weightRanking = 0; for (Tuple<String, Float> nodeWeight : nodeWeights) { NodeAllocationResult current = nodeExplanationMap.get(nodeWeight.v1()); nodeDecisions.add(new NodeAllocationResult(current.getNode(), current.getCanAllocateDecision(), ++weightRanking)); } } return AllocateUnassignedDecision.fromDecision(decision, minNode != null ? minNode.routingNode.node() : null, nodeDecisions); } /** * Decide whether to take a new allocation decision/weight over the existing allocation decision/weight * <p> * We take the lowest weight decision, but we always prefer {@code YES} or {@code THROTTLE} decisions over {@code NOT_PREFERRED} * * @param newDecision The new decision * @param newWeight The new weight * @param existingDecision The existing decision, or null if there is no existing decision * @param existingWeight The existing weight, or {@link Float#POSITIVE_INFINITY} if there is no existing weight * @return true to take the new decision/weight, false to keep the existing decision/weight */ private static boolean preferNewDecisionOverExisting( Decision newDecision, float newWeight, @Nullable Decision existingDecision, float existingWeight ) { assert newDecision != null : "newDecision should never be null"; assert newDecision.type() == Type.YES || newDecision.type() == Type.NOT_PREFERRED || newDecision.type() == Type.THROTTLE : "unsupported decision type: " + newDecision.type(); assert newWeight != existingWeight : "Equal weights should be handled elsewhere"; if (existingDecision == null) { // This is the first YES/NOT_PREFERRED/THROTTLE decision we've seen, take it return true; } else if (existingDecision.type() == newDecision.type()) { // Decision types are the same, take the lower weight return newWeight < existingWeight; } else { // Decision types are different, take the lower weight unless it's NOT_PREFERRED float adjustedNewWeight = newDecision.type() == Type.NOT_PREFERRED ? Float.POSITIVE_INFINITY : newWeight; float adjustedExistingWeight = existingDecision.type() == Type.NOT_PREFERRED ? Float.POSITIVE_INFINITY : existingWeight; return adjustedNewWeight < adjustedExistingWeight; } } private static final Comparator<ShardRouting> BY_DESCENDING_SHARD_ID = (s1, s2) -> Integer.compare(s2.id(), s1.id()); /** * Scratch space for accumulating/sorting the {@link ShardRouting} instances when contemplating moving the shards away from a node * in {@link #tryRelocateShard} - re-used to avoid extraneous allocations etc. */ private ShardRouting[] shardRoutingsOnMaxWeightNode; /** * Tries to find a relocation from the max node to the minimal node for an arbitrary shard of the given index on the * balance model. Iff this method returns a <code>true</code> the relocation has already been executed on the * simulation model as well as on the cluster. */ private boolean tryRelocateShard(ModelNode minNode, ModelNode maxNode, ProjectIndex idx) { final ModelIndex index = maxNode.getIndex(idx); if (index != null) { logger.trace("Try relocating shard of [{}] from [{}] to [{}]", idx, maxNode.getNodeId(), minNode.getNodeId()); if (shardRoutingsOnMaxWeightNode == null || shardRoutingsOnMaxWeightNode.length < index.numShards()) { shardRoutingsOnMaxWeightNode = new ShardRouting[index.numShards() * 2]; // oversized so reuse is more likely } int startedShards = 0; for (final var shardRouting : index) { if (shardRouting.started()) { // cannot rebalance unassigned, initializing or relocating shards anyway shardRoutingsOnMaxWeightNode[startedShards] = shardRouting; startedShards += 1; } } // check in descending order of shard id so that the decision is deterministic ArrayUtil.timSort(shardRoutingsOnMaxWeightNode, 0, startedShards, BY_DESCENDING_SHARD_ID); final AllocationDeciders deciders = allocation.deciders(); for (int shardIndex = 0; shardIndex < startedShards; shardIndex++) { final ShardRouting shard = shardRoutingsOnMaxWeightNode[shardIndex]; final Decision rebalanceDecision = deciders.canRebalance(shard, allocation); if (rebalanceDecision.type() == Type.NO) { continue; } final Decision allocationDecision = deciders.canAllocate(shard, minNode.getRoutingNode(), allocation); if (allocationDecision.type() == Type.NO || allocationDecision.type() == Type.NOT_PREFERRED) { continue; } final Decision.Type canAllocateOrRebalance = Decision.Type.min(allocationDecision.type(), rebalanceDecision.type()); maxNode.removeShard(projectIndex(shard), shard); long shardSize = allocation.clusterInfo().getShardSize(shard, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE); assert canAllocateOrRebalance == Type.YES || canAllocateOrRebalance == Type.THROTTLE : canAllocateOrRebalance; logger.debug( "decision [{}]: relocate [{}] from [{}] to [{}]", canAllocateOrRebalance, shard, maxNode.getNodeId(), minNode.getNodeId() ); minNode.addShard( projectIndex(shard), canAllocateOrRebalance == Type.YES /* only allocate on the cluster if we are not throttled */ ? routingNodes.relocateShard(shard, minNode.getNodeId(), shardSize, "rebalance", allocation.changes()).v1() : shard.relocate(minNode.getNodeId(), shardSize) ); return true; } } logger.trace("No shards of [{}] can relocate from [{}] to [{}]", idx, maxNode.getNodeId(), minNode.getNodeId()); return false; } // Visible for testing. public RoutingAllocation getAllocation() { return this.allocation; } } public static
PrioritiseByShardWriteLoadComparator
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/LogicalPlanBuilder.java
{ "start": 6575, "end": 64058 }
class ____ extends ExpressionBuilder { private static final String TIME = "time", START = "start", END = "end", STEP = "step"; private static final Set<String> PROMQL_ALLOWED_PARAMS = Set.of(TIME, START, END, STEP); /** * Maximum number of commands allowed per query */ public static final int MAX_QUERY_DEPTH = 500; public LogicalPlanBuilder(ParsingContext context) { super(context); } private int queryDepth = 0; protected EsqlStatement statement(ParseTree ctx) { EsqlStatement p = typedParsing(this, ctx, EsqlStatement.class); return p; } protected LogicalPlan plan(ParseTree ctx) { LogicalPlan p = ParserUtils.typedParsing(this, ctx, LogicalPlan.class); if (p instanceof Explain == false && p.anyMatch(logicalPlan -> logicalPlan instanceof Explain)) { throw new ParsingException(source(ctx), "EXPLAIN does not support downstream commands"); } if (p instanceof Explain explain && explain.query().anyMatch(logicalPlan -> logicalPlan instanceof Explain)) { // TODO this one is never reached because the Parser fails to understand multiple round brackets throw new ParsingException(source(ctx), "EXPLAIN cannot be used inside another EXPLAIN command"); } var errors = this.context.params().parsingErrors(); if (errors.hasNext() == false) { return p; } else { throw ParsingException.combineParsingExceptions(errors); } } @Override public EsqlStatement visitStatements(EsqlBaseParser.StatementsContext ctx) { List<QuerySetting> settings = new ArrayList<>(); for (EsqlBaseParser.SetCommandContext setCommandContext : ctx.setCommand()) { settings.add(visitSetCommand(setCommandContext)); } LogicalPlan query = visitSingleStatement(ctx.singleStatement()); return new EsqlStatement(query, settings); } protected List<LogicalPlan> plans(List<? extends ParserRuleContext> ctxs) { return ParserUtils.visitList(this, ctxs, LogicalPlan.class); } @Override public LogicalPlan visitSingleStatement(EsqlBaseParser.SingleStatementContext ctx) { var plan = plan(ctx.query()); telemetryAccounting(plan); return plan; } @Override public QuerySetting visitSetCommand(EsqlBaseParser.SetCommandContext ctx) { var field = visitSetField(ctx.setField()); return new QuerySetting(source(ctx), field); } @Override public Alias visitSetField(EsqlBaseParser.SetFieldContext ctx) { String name = visitIdentifier(ctx.identifier()); Expression value = expression(ctx.constant()); return new Alias(source(ctx), name, value); } @Override public LogicalPlan visitCompositeQuery(EsqlBaseParser.CompositeQueryContext ctx) { queryDepth++; if (queryDepth > MAX_QUERY_DEPTH) { throw new ParsingException( "ESQL statement exceeded the maximum query depth allowed ({}): [{}]", MAX_QUERY_DEPTH, ctx.getText() ); } try { LogicalPlan input = plan(ctx.query()); telemetryAccounting(input); PlanFactory makePlan = typedParsing(this, ctx.processingCommand(), PlanFactory.class); return makePlan.apply(input); } finally { queryDepth--; } } private LogicalPlan telemetryAccounting(LogicalPlan node) { if (node instanceof TelemetryAware ma) { this.context.telemetry().command(ma); } return node; } @Override public PlanFactory visitEvalCommand(EsqlBaseParser.EvalCommandContext ctx) { return p -> new Eval(source(ctx), p, visitFields(ctx.fields())); } @Override public PlanFactory visitGrokCommand(EsqlBaseParser.GrokCommandContext ctx) { return p -> { Source source = source(ctx); FoldContext patternFoldContext = FoldContext.small(); /* TODO remove me */ List<String> patterns = ctx.string() .stream() .map(stringContext -> BytesRefs.toString(visitString(stringContext).fold(patternFoldContext))) .toList(); for (int i = 0; i < patterns.size(); i++) { String pattern = patterns.get(i); // Validate each pattern individually, // as multiple invalid patterns could be combined to form a valid one // see https://github.com/elastic/elasticsearch/issues/136750 try { Grok.pattern(source, pattern); } catch (SyntaxException e) { throw new ParsingException(source(ctx.string(i)), "Invalid GROK pattern [{}]: [{}]", pattern, e.getMessage()); } } String combinePattern = org.elasticsearch.grok.Grok.combinePatterns(patterns); Grok.Parser grokParser = Grok.pattern(source, combinePattern); validateGrokPattern(source, grokParser, combinePattern, patterns); Grok result = new Grok(source(ctx), p, expression(ctx.primaryExpression()), grokParser); return result; }; } private void validateGrokPattern(Source source, Grok.Parser grokParser, String pattern, List<String> originalPatterns) { Map<String, DataType> definedAttributes = new HashMap<>(); for (Attribute field : grokParser.extractedFields()) { String name = field.name(); DataType type = field.dataType(); DataType prev = definedAttributes.put(name, type); if (prev != null) { if (originalPatterns.size() == 1) { throw new ParsingException( source, "Invalid GROK pattern [{}]: the attribute [{}] is defined multiple times with different types", originalPatterns.getFirst(), name ); } else { throw new ParsingException( source, "Invalid GROK patterns {}: the attribute [{}] is defined multiple times with different types", originalPatterns, name ); } } } } @Override public PlanFactory visitDissectCommand(EsqlBaseParser.DissectCommandContext ctx) { return p -> { String pattern = BytesRefs.toString(visitString(ctx.string()).fold(FoldContext.small() /* TODO remove me */)); Map<String, Object> options = visitDissectCommandOptions(ctx.dissectCommandOptions()); String appendSeparator = ""; for (Map.Entry<String, Object> item : options.entrySet()) { if (item.getKey().equalsIgnoreCase("append_separator") == false) { throw new ParsingException(source(ctx), "Invalid option for dissect: [{}]", item.getKey()); } if (item.getValue() instanceof BytesRef == false) { throw new ParsingException( source(ctx), "Invalid value for dissect append_separator: expected a string, but was [{}]", item.getValue() ); } appendSeparator = BytesRefs.toString(item.getValue()); } Source src = source(ctx); try { DissectParser parser = new DissectParser(pattern, appendSeparator); Set<String> referenceKeys = parser.referenceKeys(); if (referenceKeys.isEmpty() == false) { throw new ParsingException( src, "Reference keys not supported in dissect patterns: [%{*{}}]", referenceKeys.iterator().next() ); } Dissect.Parser esqlDissectParser = new Dissect.Parser(pattern, appendSeparator, parser); List<Attribute> keys = esqlDissectParser.keyAttributes(src); return new Dissect(src, p, expression(ctx.primaryExpression()), esqlDissectParser, keys); } catch (DissectException e) { throw new ParsingException(src, "Invalid pattern for dissect: [{}]", pattern); } }; } @Override public PlanFactory visitMvExpandCommand(EsqlBaseParser.MvExpandCommandContext ctx) { UnresolvedAttribute field = visitQualifiedName(ctx.qualifiedName()); Source src = source(ctx); return child -> new MvExpand(src, child, field, new UnresolvedAttribute(src, field.qualifier(), field.name(), null)); } @Override public Map<String, Object> visitDissectCommandOptions(EsqlBaseParser.DissectCommandOptionsContext ctx) { if (ctx == null) { return Map.of(); } Map<String, Object> result = new HashMap<>(); for (EsqlBaseParser.DissectCommandOptionContext option : ctx.dissectCommandOption()) { result.put(visitIdentifier(option.identifier()), expression(option.constant()).fold(FoldContext.small() /* TODO remove me */)); } return result; } @Override @SuppressWarnings("unchecked") public LogicalPlan visitRowCommand(EsqlBaseParser.RowCommandContext ctx) { return new Row(source(ctx), (List<Alias>) (List) mergeOutputExpressions(visitFields(ctx.fields()), List.of())); } private LogicalPlan visitRelation(Source source, IndexMode indexMode, EsqlBaseParser.IndexPatternAndMetadataFieldsContext ctx) { List<EsqlBaseParser.IndexPatternOrSubqueryContext> ctxs = ctx == null ? null : ctx.indexPatternOrSubquery(); List<EsqlBaseParser.IndexPatternContext> indexPatternsCtx = new ArrayList<>(); List<EsqlBaseParser.SubqueryContext> subqueriesCtx = new ArrayList<>(); if (ctxs != null) { ctxs.forEach(c -> { if (c.indexPattern() != null) { indexPatternsCtx.add(c.indexPattern()); } else { subqueriesCtx.add(c.subquery()); } }); } IndexPattern table = new IndexPattern(source, visitIndexPattern(indexPatternsCtx)); List<Subquery> subqueries = visitSubqueriesInFromCommand(subqueriesCtx); Map<String, Attribute> metadataMap = new LinkedHashMap<>(); if (ctx.metadata() != null) { for (var c : ctx.metadata().UNQUOTED_SOURCE()) { String id = c.getText(); Source src = source(c); if (MetadataAttribute.isSupported(id) == false) { throw new ParsingException(src, "unsupported metadata field [" + id + "]"); } Attribute a = metadataMap.put(id, MetadataAttribute.create(src, id)); if (a != null) { throw new ParsingException(src, "metadata field [" + id + "] already declared [" + a.source().source() + "]"); } } } List<Attribute> metadataFields = List.of(metadataMap.values().toArray(Attribute[]::new)); final String commandName = indexMode == IndexMode.TIME_SERIES ? "TS" : "FROM"; UnresolvedRelation unresolvedRelation = new UnresolvedRelation(source, table, false, metadataFields, indexMode, null, commandName); if (subqueries.isEmpty()) { return unresolvedRelation; } else { // subquery is not supported with time-series indices at the moment if (indexMode == IndexMode.TIME_SERIES) { throw new ParsingException(source, "Subqueries are not supported in TS command"); } List<LogicalPlan> mainQueryAndSubqueries = new ArrayList<>(subqueries.size() + 1); if (table.indexPattern().isEmpty() == false) { mainQueryAndSubqueries.add(unresolvedRelation); telemetryAccounting(unresolvedRelation); } mainQueryAndSubqueries.addAll(subqueries); if (mainQueryAndSubqueries.size() == 1) { // if there is only one child, return it directly, no need for UnionAll return table.indexPattern().isEmpty() ? subqueries.get(0).plan() : unresolvedRelation; } else { // the output of UnionAll is resolved by analyzer return new UnionAll(source(ctxs.getFirst(), ctxs.getLast()), mainQueryAndSubqueries, List.of()); } } } private List<Subquery> visitSubqueriesInFromCommand(List<EsqlBaseParser.SubqueryContext> ctxs) { if (EsqlCapabilities.Cap.SUBQUERY_IN_FROM_COMMAND.isEnabled() == false) { return List.of(); } if (ctxs == null) { return List.of(); } List<Subquery> subqueries = new ArrayList<>(); for (EsqlBaseParser.SubqueryContext ctx : ctxs) { LogicalPlan plan = visitSubquery(ctx); subqueries.add(new Subquery(source(ctx), plan)); } return subqueries; } @Override public LogicalPlan visitSubquery(EsqlBaseParser.SubqueryContext ctx) { // build a subquery tree EsqlBaseParser.FromCommandContext fromCtx = ctx.fromCommand(); LogicalPlan plan = visitFromCommand(fromCtx); List<PlanFactory> processingCommands = visitList(this, ctx.processingCommand(), PlanFactory.class); for (PlanFactory processingCommand : processingCommands) { telemetryAccounting(plan); plan = processingCommand.apply(plan); } telemetryAccounting(plan); return plan; } @Override public LogicalPlan visitFromCommand(EsqlBaseParser.FromCommandContext ctx) { return visitRelation(source(ctx), IndexMode.STANDARD, ctx.indexPatternAndMetadataFields()); } @Override public PlanFactory visitInsistCommand(EsqlBaseParser.InsistCommandContext ctx) { var source = source(ctx); List<NamedExpression> fields = visitQualifiedNamePatterns(ctx.qualifiedNamePatterns(), ne -> { if (ne instanceof UnresolvedStar || ne instanceof UnresolvedNamePattern) { Source neSource = ne.source(); throw new ParsingException(neSource, "INSIST doesn't support wildcards, found [{}]", neSource.text()); } }); return input -> new Insist( source, input, fields.stream().map(ne -> (Attribute) new UnresolvedAttribute(ne.source(), ne.name())).toList() ); } @Override public PlanFactory visitStatsCommand(EsqlBaseParser.StatsCommandContext ctx) { final Stats stats = stats(source(ctx), ctx.grouping, ctx.stats); // Only the first STATS command in a TS query is treated as the time-series aggregation return input -> { if (input.anyMatch(p -> p instanceof Aggregate) == false && input.anyMatch(p -> p instanceof UnresolvedRelation ur && ur.indexMode() == IndexMode.TIME_SERIES)) { return new TimeSeriesAggregate(source(ctx), input, stats.groupings, stats.aggregates, null); } else { return new Aggregate(source(ctx), input, stats.groupings, stats.aggregates); } }; } private record Stats(List<Expression> groupings, List<? extends NamedExpression> aggregates) {} private Stats stats(Source source, EsqlBaseParser.FieldsContext groupingsCtx, EsqlBaseParser.AggFieldsContext aggregatesCtx) { List<NamedExpression> groupings = visitGrouping(groupingsCtx); List<NamedExpression> aggregates = new ArrayList<>(visitAggFields(aggregatesCtx)); if (aggregates.isEmpty() && groupings.isEmpty()) { throw new ParsingException(source, "At least one aggregation or grouping expression required in [{}]", source.text()); } // grouping keys are automatically added as aggregations however the user is not allowed to specify them if (groupings.isEmpty() == false && aggregates.isEmpty() == false) { var groupNames = new LinkedHashSet<>(Expressions.names(groupings)); var groupRefNames = new LinkedHashSet<>(Expressions.names(Expressions.references(groupings))); for (NamedExpression aggregate : aggregates) { Expression e = Alias.unwrap(aggregate); if (e.resolved() == false && e instanceof UnresolvedFunction == false) { String name = e.sourceText(); if (groupNames.contains(name)) { fail(e, "grouping key [{}] already specified in the STATS BY clause", name); } else if (groupRefNames.contains(name)) { fail(e, "Cannot specify grouping expression [{}] as an aggregate", name); } } } } // since groupings are aliased, add refs to it in the aggregates for (Expression group : groupings) { aggregates.add(Expressions.attribute(group)); } return new Stats(new ArrayList<>(groupings), aggregates); } private void fail(Expression exp, String message, Object... args) { throw new VerificationException(Collections.singletonList(Failure.fail(exp, message, args))); } @Override public PlanFactory visitInlineStatsCommand(EsqlBaseParser.InlineStatsCommandContext ctx) { var source = source(ctx); if (false == EsqlCapabilities.Cap.INLINE_STATS.isEnabled()) { throw new ParsingException(source, "INLINE STATS command currently requires a snapshot build"); } // TODO: drop after next minor release if (ctx.INLINESTATS() != null) { HeaderWarning.addWarning( "Line {}:{}: INLINESTATS is deprecated, use INLINE STATS instead", source.source().getLineNumber(), source.source().getColumnNumber() ); } List<Alias> aggFields = visitAggFields(ctx.stats); List<NamedExpression> aggregates = new ArrayList<>(aggFields); List<NamedExpression> groupings = visitGrouping(ctx.grouping); aggregates.addAll(groupings); return input -> new InlineStats(source, new Aggregate(source, input, new ArrayList<>(groupings), aggregates)); } @Override public PlanFactory visitWhereCommand(EsqlBaseParser.WhereCommandContext ctx) { Expression expression = expression(ctx.booleanExpression()); return input -> new Filter(source(ctx), input, expression); } @Override public PlanFactory visitLimitCommand(EsqlBaseParser.LimitCommandContext ctx) { Source source = source(ctx); Object val = expression(ctx.constant()).fold(FoldContext.small() /* TODO remove me */); if (val instanceof Integer i && i >= 0) { return input -> new Limit(source, new Literal(source, i, DataType.INTEGER), input); } String valueType = expression(ctx.constant()).dataType().typeName(); throw new ParsingException( source, "value of [" + source.text() + "] must be a non negative integer, found value [" + ctx.constant().getText() + "] type [" + valueType + "]" ); } @Override public PlanFactory visitSortCommand(EsqlBaseParser.SortCommandContext ctx) { List<Order> orders = visitList(this, ctx.orderExpression(), Order.class); Source source = source(ctx); return input -> new OrderBy(source, input, orders); } @Override public Explain visitExplainCommand(EsqlBaseParser.ExplainCommandContext ctx) { return new Explain(source(ctx), plan(ctx.subqueryExpression().query())); } @Override public PlanFactory visitDropCommand(EsqlBaseParser.DropCommandContext ctx) { List<NamedExpression> removals = visitQualifiedNamePatterns(ctx.qualifiedNamePatterns(), ne -> { if (ne instanceof UnresolvedStar) { var src = ne.source(); throw new ParsingException(src, "Removing all fields is not allowed [{}]", src.text()); } }); return child -> new Drop(source(ctx), child, removals); } @Override public PlanFactory visitRenameCommand(EsqlBaseParser.RenameCommandContext ctx) { List<Alias> renamings = ctx.renameClause().stream().map(this::visitRenameClause).toList(); return child -> new Rename(source(ctx), child, renamings); } @Override public PlanFactory visitKeepCommand(EsqlBaseParser.KeepCommandContext ctx) { final Holder<Boolean> hasSeenStar = new Holder<>(false); List<NamedExpression> projections = visitQualifiedNamePatterns(ctx.qualifiedNamePatterns(), ne -> { if (ne instanceof UnresolvedStar) { if (hasSeenStar.get()) { var src = ne.source(); throw new ParsingException(src, "Cannot specify [*] more than once", src.text()); } else { hasSeenStar.set(Boolean.TRUE); } } }); return child -> new Keep(source(ctx), child, projections); } @Override public LogicalPlan visitShowInfo(EsqlBaseParser.ShowInfoContext ctx) { return new ShowInfo(source(ctx)); } @Override public PlanFactory visitEnrichCommand(EsqlBaseParser.EnrichCommandContext ctx) { return child -> { var source = source(ctx); Tuple<Mode, String> tuple = parsePolicyName(ctx.policyName); Mode mode = tuple.v1(); String policyNameString = tuple.v2(); NamedExpression matchField = ctx.ON() != null ? visitQualifiedNamePattern(ctx.matchField) : new EmptyAttribute(source); String patternString = matchField instanceof UnresolvedNamePattern up ? up.pattern() : matchField instanceof UnresolvedStar ? WILDCARD : null; if (patternString != null) { throw new ParsingException( source, "Using wildcards [*] in ENRICH WITH projections is not allowed, found [{}]", patternString ); } List<NamedExpression> keepClauses = visitList(this, ctx.enrichWithClause(), NamedExpression.class); // If this is a remote-only ENRICH, any upstream LOOKUP JOINs need to be treated as remote-only, too. if (mode == Mode.REMOTE) { child = child.transformDown(LookupJoin.class, lj -> new LookupJoin(lj.source(), lj.left(), lj.right(), lj.config(), true)); } return new Enrich( source, child, mode, Literal.keyword(source(ctx.policyName), policyNameString), matchField, null, Map.of(), keepClauses.isEmpty() ? List.of() : keepClauses ); }; } @Override public PlanFactory visitChangePointCommand(EsqlBaseParser.ChangePointCommandContext ctx) { Source src = source(ctx); Attribute value = visitQualifiedName(ctx.value); Attribute key = ctx.key == null ? new UnresolvedAttribute(src, "@timestamp") : visitQualifiedName(ctx.key); UnresolvedAttribute parsedTargetTypeColumn = visitQualifiedName(ctx.targetType); UnresolvedAttribute parsedTargetPvalueColumn = visitQualifiedName(ctx.targetPvalue); if (parsedTargetTypeColumn != null && parsedTargetTypeColumn.qualifier() != null) { throw qualifiersUnsupportedInFieldDefinitions(parsedTargetTypeColumn.source(), ctx.targetType.getText()); } if (parsedTargetPvalueColumn != null && parsedTargetPvalueColumn.qualifier() != null) { throw qualifiersUnsupportedInFieldDefinitions(parsedTargetPvalueColumn.source(), ctx.targetPvalue.getText()); } Attribute targetType = new ReferenceAttribute( src, null, parsedTargetTypeColumn == null ? "type" : parsedTargetTypeColumn.name(), DataType.KEYWORD ); Attribute targetPvalue = new ReferenceAttribute( src, null, parsedTargetPvalueColumn == null ? "pvalue" : parsedTargetPvalueColumn.name(), DataType.DOUBLE ); return child -> new ChangePoint(src, child, value, key, targetType, targetPvalue); } private static Tuple<Mode, String> parsePolicyName(EsqlBaseParser.EnrichPolicyNameContext ctx) { String stringValue; if (ctx.ENRICH_POLICY_NAME() != null) { stringValue = ctx.ENRICH_POLICY_NAME().getText(); } else { stringValue = ctx.QUOTED_STRING().getText(); stringValue = stringValue.substring(1, stringValue.length() - 1); } int index = stringValue.indexOf(":"); Mode mode = null; if (index >= 0) { String modeValue = stringValue.substring(0, index); if (modeValue.startsWith("_")) { mode = Mode.from(modeValue.substring(1)); } if (mode == null) { throw new ParsingException( source(ctx), "Unrecognized value [{}], ENRICH policy qualifier needs to be one of {}", modeValue, Arrays.stream(Mode.values()).map(s -> "_" + s).toList() ); } } else { mode = Mode.ANY; } String policyName = index < 0 ? stringValue : stringValue.substring(index + 1); return new Tuple<>(mode, policyName); } @Override public LogicalPlan visitTimeSeriesCommand(EsqlBaseParser.TimeSeriesCommandContext ctx) { return visitRelation(source(ctx), IndexMode.TIME_SERIES, ctx.indexPatternAndMetadataFields()); } @Override public PlanFactory visitLookupCommand(EsqlBaseParser.LookupCommandContext ctx) { if (false == Build.current().isSnapshot()) { throw new ParsingException(source(ctx), "LOOKUP__ is in preview and only available in SNAPSHOT build"); } var source = source(ctx); @SuppressWarnings("unchecked") List<Attribute> matchFields = (List<Attribute>) (List) visitQualifiedNamePatterns(ctx.qualifiedNamePatterns(), ne -> { if (ne instanceof UnresolvedNamePattern || ne instanceof UnresolvedStar) { var src = ne.source(); throw new ParsingException(src, "Using wildcards [*] in LOOKUP ON is not allowed yet [{}]", src.text()); } if ((ne instanceof UnresolvedAttribute) == false) { throw new IllegalStateException( "visitQualifiedNamePatterns can only return UnresolvedNamePattern, UnresolvedStar or UnresolvedAttribute" ); } }); Literal tableName = Literal.keyword(source, visitIndexPattern(List.of(ctx.indexPattern()))); return p -> new Lookup(source, p, tableName, matchFields, null /* localRelation will be resolved later*/); } @Override public PlanFactory visitJoinCommand(EsqlBaseParser.JoinCommandContext ctx) { var source = source(ctx); if (false == EsqlCapabilities.Cap.JOIN_LOOKUP_V12.isEnabled()) { throw new ParsingException(source, "JOIN is in preview and only available in SNAPSHOT build"); } if (ctx.type != null && ctx.type.getType() != EsqlBaseParser.JOIN_LOOKUP) { String joinType = ctx.type == null ? "(INNER)" : ctx.type.getText(); throw new ParsingException(source, "only LOOKUP JOIN available, {} JOIN unsupported at the moment", joinType); } var target = ctx.joinTarget(); var rightPattern = visitIndexPattern(List.of(target.index)); if (rightPattern.contains(WILDCARD)) { throw new ParsingException(source(target), "invalid index pattern [{}], * is not allowed in LOOKUP JOIN", rightPattern); } if (RemoteClusterAware.isRemoteIndexName(rightPattern)) { throw new ParsingException( source(target), "invalid index pattern [{}], remote clusters are not supported with LOOKUP JOIN", rightPattern ); } if (rightPattern.contains(IndexNameExpressionResolver.SelectorResolver.SELECTOR_SEPARATOR)) { throw new ParsingException( source(target), "invalid index pattern [{}], index pattern selectors are not supported in LOOKUP JOIN", rightPattern ); } UnresolvedRelation right = new UnresolvedRelation( source(target), new IndexPattern(source(target.index), rightPattern), false, emptyList(), IndexMode.LOOKUP, null ); var condition = ctx.joinCondition(); var joinInfo = typedParsing(this, condition, JoinInfo.class); return p -> { boolean hasRemotes = p.anyMatch(node -> { if (node instanceof UnresolvedRelation r) { return Arrays.stream(Strings.splitStringByCommaToArray(r.indexPattern().indexPattern())) .anyMatch(RemoteClusterAware::isRemoteIndexName); } else { return false; } }); if (hasRemotes && EsqlCapabilities.Cap.ENABLE_LOOKUP_JOIN_ON_REMOTE.isEnabled() == false) { throw new ParsingException(source, "remote clusters are not supported with LOOKUP JOIN"); } return new LookupJoin( source, p, right, joinInfo.joinFields(), hasRemotes, Predicates.combineAndWithSource(joinInfo.joinExpressions(), source(condition)) ); }; } private record JoinInfo(List<Attribute> joinFields, List<Expression> joinExpressions) {} @Override public JoinInfo visitJoinCondition(EsqlBaseParser.JoinConditionContext ctx) { var expressions = visitList(this, ctx.booleanExpression(), Expression.class); if (expressions.isEmpty()) { throw new ParsingException(source(ctx), "JOIN ON clause cannot be empty"); } // Inspect the first expression to determine the type of join (field-based or expression-based) // We treat literals as field-based as it is more likely the user was trying to write a field name // and so the field based error message is more helpful boolean isFieldBased = expressions.get(0) instanceof UnresolvedAttribute || expressions.get(0) instanceof Literal; if (isFieldBased) { return processFieldBasedJoin(expressions); } else { return processExpressionBasedJoin(expressions, ctx); } } private JoinInfo processFieldBasedJoin(List<Expression> expressions) { List<Attribute> joinFields = new ArrayList<>(expressions.size()); for (var f : expressions) { // verify each field is an unresolved attribute if (f instanceof UnresolvedAttribute ua) { if (ua.qualifier() != null) { throw new ParsingException( ua.source(), "JOIN ON clause only supports unqualified fields, found [{}]", ua.qualifiedName() ); } joinFields.add(ua); } else { throw new ParsingException( f.source(), "JOIN ON clause must be a comma separated list of fields or a single expression, found [{}]", f.sourceText() ); } } validateJoinFields(joinFields); return new JoinInfo(joinFields, emptyList()); } private JoinInfo processExpressionBasedJoin(List<Expression> expressions, EsqlBaseParser.JoinConditionContext ctx) { if (LOOKUP_JOIN_ON_BOOLEAN_EXPRESSION.isEnabled() == false) { throw new ParsingException(source(ctx), "JOIN ON clause only supports fields at the moment."); } List<Attribute> joinFields = new ArrayList<>(); List<Expression> joinExpressions = new ArrayList<>(); if (expressions.size() != 1) { throw new ParsingException( source(ctx), "JOIN ON clause with expressions only supports a single expression, found [{}]", expressions ); } expressions = Predicates.splitAnd(expressions.get(0)); for (var f : expressions) { addJoinExpression(f, joinFields, joinExpressions, ctx); } if (joinFields.isEmpty()) { throw new ParsingException( source(ctx), "JOIN ON clause with expressions must contain at least one condition relating the left index and the lookup index" ); } return new JoinInfo(joinFields, joinExpressions); } private void addJoinExpression( Expression exp, List<Attribute> joinFields, List<Expression> joinExpressions, EsqlBaseParser.JoinConditionContext ctx ) { exp = handleNegationOfEquals(exp); if (containsBareFieldsInBooleanExpression(exp)) { throw new ParsingException( source(ctx), "JOIN ON clause only supports fields or AND of Binary Expressions at the moment, found [{}]", exp.sourceText() ); } if (exp instanceof EsqlBinaryComparison comparison && comparison.left() instanceof UnresolvedAttribute left && comparison.right() instanceof UnresolvedAttribute right) { joinFields.add(left); joinFields.add(right); } joinExpressions.add(exp); } private boolean containsBareFieldsInBooleanExpression(Expression expression) { if (expression instanceof UnresolvedAttribute) { return true; // This is a bare field } if (expression instanceof EsqlBinaryComparison) { return false; // This is a binary comparison, not a bare field } if (expression instanceof BinaryLogic binaryLogic) { // Check if either side contains bare fields return containsBareFieldsInBooleanExpression(binaryLogic.left()) || containsBareFieldsInBooleanExpression(binaryLogic.right()); } // For other expression types (functions, constants, etc.), they are not bare fields return false; } private void validateJoinFields(List<Attribute> joinFields) { if (joinFields.size() > 1) { Set<String> matchFieldNames = new LinkedHashSet<>(); for (Attribute field : joinFields) { if (matchFieldNames.add(field.name()) == false) { throw new ParsingException( field.source(), "JOIN ON clause does not support multiple fields with the same name, found multiple instances of [{}]", field.name() ); } } } } private Expression handleNegationOfEquals(Expression f) { if (f instanceof Not not && not.children().size() == 1 && not.children().get(0) instanceof Equals equals) { // we only support NOT on Equals, by converting it to NotEquals return equals.negate(); } return f; } private void checkForRemoteClusters(LogicalPlan plan, Source source, String commandName) { plan.forEachUp(UnresolvedRelation.class, r -> { for (var indexPattern : Strings.splitStringByCommaToArray(r.indexPattern().indexPattern())) { if (RemoteClusterAware.isRemoteIndexName(indexPattern)) { throw new ParsingException( source, "invalid index pattern [{}], remote clusters are not supported with {}", r.indexPattern().indexPattern(), commandName ); } } }); } @Override @SuppressWarnings("unchecked") public PlanFactory visitForkCommand(EsqlBaseParser.ForkCommandContext ctx) { List<PlanFactory> subQueries = visitForkSubQueries(ctx.forkSubQueries()); if (subQueries.size() > Fork.MAX_BRANCHES) { throw new ParsingException(source(ctx), "Fork supports up to " + Fork.MAX_BRANCHES + " branches"); } return input -> { if (EsqlCapabilities.Cap.ENABLE_FORK_FOR_REMOTE_INDICES.isEnabled() == false) { checkForRemoteClusters(input, source(ctx), "FORK"); } List<LogicalPlan> subPlans = subQueries.stream().map(planFactory -> planFactory.apply(input)).toList(); return new Fork(source(ctx), subPlans, List.of()); }; } @Override public List<PlanFactory> visitForkSubQueries(EsqlBaseParser.ForkSubQueriesContext ctx) { ArrayList<PlanFactory> list = new ArrayList<>(); int count = 1; // automatic fork branch ids start at 1 NameId firstForkNameId = null; // stores the id of the first _fork for (var subQueryCtx : ctx.forkSubQuery()) { var subQuery = visitForkSubQuery(subQueryCtx); var literal = Literal.keyword(source(ctx), "fork" + count++); // align _fork id across all fork branches Alias alias = null; if (firstForkNameId == null) { alias = new Alias(source(ctx), Fork.FORK_FIELD, literal); firstForkNameId = alias.id(); } else { alias = new Alias(source(ctx), Fork.FORK_FIELD, literal, firstForkNameId); } var finalAlias = alias; PlanFactory eval = p -> new Eval(source(ctx), subQuery.apply(p), List.of(finalAlias)); list.add(eval); } return List.copyOf(list); } @Override public PlanFactory visitForkSubQuery(EsqlBaseParser.ForkSubQueryContext ctx) { var subCtx = ctx.forkSubQueryCommand(); if (subCtx instanceof EsqlBaseParser.SingleForkSubQueryCommandContext sglCtx) { return typedParsing(this, sglCtx.forkSubQueryProcessingCommand(), PlanFactory.class); } else if (subCtx instanceof EsqlBaseParser.CompositeForkSubQueryContext compCtx) { return visitCompositeForkSubQuery(compCtx); } else { throw new AssertionError("Unknown context: " + ctx); } } @Override public PlanFactory visitCompositeForkSubQuery(EsqlBaseParser.CompositeForkSubQueryContext ctx) { PlanFactory lowerPlan = ParserUtils.typedParsing(this, ctx.forkSubQueryCommand(), PlanFactory.class); PlanFactory makePlan = typedParsing(this, ctx.forkSubQueryProcessingCommand(), PlanFactory.class); return input -> makePlan.apply(lowerPlan.apply(input)); } @Override public PlanFactory visitFuseCommand(EsqlBaseParser.FuseCommandContext ctx) { Source source = source(ctx); return input -> { Attribute scoreAttr = visitFuseScoreBy(ctx.fuseConfiguration(), source); Attribute discriminatorAttr = visitFuseGroupBy(ctx.fuseConfiguration(), source); List<NamedExpression> keys = visitFuseKeyBy(ctx.fuseConfiguration(), source); MapExpression options = visitFuseOptions(ctx.fuseConfiguration()); String fuseTypeName = ctx.fuseType == null ? Fuse.FuseType.RRF.name() : visitIdentifier(ctx.fuseType); Fuse.FuseType fuseType; try { fuseType = Fuse.FuseType.valueOf(fuseTypeName.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { throw new ParsingException(source(ctx), "Fuse type " + fuseTypeName + " is not supported"); } return new Fuse(source, input, scoreAttr, discriminatorAttr, keys, fuseType, options); }; } private Attribute visitFuseScoreBy(List<EsqlBaseParser.FuseConfigurationContext> fuseConfigurationContexts, Source source) { Attribute scoreAttr = null; for (EsqlBaseParser.FuseConfigurationContext fuseConfigurationContext : fuseConfigurationContexts) { if (fuseConfigurationContext.score != null) { if (scoreAttr != null) { throw new ParsingException(source(fuseConfigurationContext), "Only one SCORE BY can be specified"); } scoreAttr = visitQualifiedName(fuseConfigurationContext.score); } } return scoreAttr == null ? new UnresolvedAttribute(source, MetadataAttribute.SCORE) : scoreAttr; } private Attribute visitFuseGroupBy(List<EsqlBaseParser.FuseConfigurationContext> fuseConfigurationContexts, Source source) { Attribute groupByAttr = null; for (EsqlBaseParser.FuseConfigurationContext fuseConfigurationContext : fuseConfigurationContexts) { if (fuseConfigurationContext.group != null) { if (groupByAttr != null) { throw new ParsingException(source(fuseConfigurationContext), "Only one GROUP BY can be specified"); } groupByAttr = visitQualifiedName(fuseConfigurationContext.group); } } return groupByAttr == null ? new UnresolvedAttribute(source, Fork.FORK_FIELD) : groupByAttr; } private List<NamedExpression> visitFuseKeyBy(List<EsqlBaseParser.FuseConfigurationContext> fuseConfigurationContexts, Source source) { List<NamedExpression> keys = null; for (EsqlBaseParser.FuseConfigurationContext fuseConfigurationContext : fuseConfigurationContexts) { if (fuseConfigurationContext.key != null) { if (keys != null) { throw new ParsingException(source(fuseConfigurationContext), "Only one KEY BY can be specified"); } keys = visitGrouping(fuseConfigurationContext.key); } } return keys == null ? List.of(new UnresolvedAttribute(source, IdFieldMapper.NAME), new UnresolvedAttribute(source, MetadataAttribute.INDEX)) : keys; } private MapExpression visitFuseOptions(List<EsqlBaseParser.FuseConfigurationContext> fuseConfigurationContexts) { MapExpression options = null; for (EsqlBaseParser.FuseConfigurationContext fuseConfigurationContext : fuseConfigurationContexts) { if (fuseConfigurationContext.options != null) { if (options != null) { throw new ParsingException(source(fuseConfigurationContext), "Only one WITH can be specified"); } options = visitMapExpression(fuseConfigurationContext.options); } } return options; } @Override public PlanFactory visitRerankCommand(EsqlBaseParser.RerankCommandContext ctx) { Source source = source(ctx); List<Alias> rerankFields = visitRerankFields(ctx.rerankFields()); Expression queryText = expression(ctx.queryText); Attribute scoreAttribute = visitQualifiedName(ctx.targetField, new UnresolvedAttribute(source, MetadataAttribute.SCORE)); if (scoreAttribute.qualifier() != null) { throw qualifiersUnsupportedInFieldDefinitions(scoreAttribute.source(), ctx.targetField.getText()); } return p -> { checkForRemoteClusters(p, source, "RERANK"); return applyRerankOptions(new Rerank(source, p, queryText, rerankFields, scoreAttribute), ctx.commandNamedParameters()); }; } private Rerank applyRerankOptions(Rerank rerank, EsqlBaseParser.CommandNamedParametersContext ctx) { MapExpression optionExpression = visitCommandNamedParameters(ctx); if (optionExpression == null) { return rerank; } Map<String, Expression> optionsMap = optionExpression.keyFoldedMap(); Expression inferenceId = optionsMap.remove(Rerank.INFERENCE_ID_OPTION_NAME); if (inferenceId != null) { rerank = applyInferenceId(rerank, inferenceId); } if (optionsMap.isEmpty() == false) { throw new ParsingException( source(ctx), "Inavalid option [{}] in RERANK, expected one of [{}]", optionsMap.keySet().stream().findAny().get(), rerank.validOptionNames() ); } return rerank; } public PlanFactory visitCompletionCommand(EsqlBaseParser.CompletionCommandContext ctx) { Source source = source(ctx); Expression prompt = expression(ctx.prompt); Attribute targetField = visitQualifiedName(ctx.targetField, new UnresolvedAttribute(source, Completion.DEFAULT_OUTPUT_FIELD_NAME)); if (targetField.qualifier() != null) { throw qualifiersUnsupportedInFieldDefinitions(targetField.source(), ctx.targetField.getText()); } return p -> { checkForRemoteClusters(p, source, "COMPLETION"); return applyCompletionOptions(new Completion(source, p, prompt, targetField), ctx.commandNamedParameters()); }; } private Completion applyCompletionOptions(Completion completion, EsqlBaseParser.CommandNamedParametersContext ctx) { MapExpression optionsExpression = ctx == null ? null : visitCommandNamedParameters(ctx); if (optionsExpression == null || optionsExpression.containsKey(Completion.INFERENCE_ID_OPTION_NAME) == false) { // Having a mandatory named parameter for inference_id is an antipattern, but it will be optional in the future when we have a // default LLM. It is better to keep inference_id as a named parameter and relax the syntax when it will become optional than // completely change the syntax in the future. throw new ParsingException( completion.source(), "Missing mandatory option [{}] in COMPLETION", Completion.INFERENCE_ID_OPTION_NAME ); } Map<String, Expression> optionsMap = optionsExpression.keyFoldedMap(); Expression inferenceId = optionsMap.remove(Completion.INFERENCE_ID_OPTION_NAME); if (inferenceId != null) { completion = applyInferenceId(completion, inferenceId); } if (optionsMap.isEmpty() == false) { throw new ParsingException( source(ctx), "Inavalid option [{}] in COMPLETION, expected one of [{}]", optionsMap.keySet().stream().findAny().get(), completion.validOptionNames() ); } return completion; } private <InferencePlanType extends InferencePlan<InferencePlanType>> InferencePlanType applyInferenceId( InferencePlanType inferencePlan, Expression inferenceId ) { if ((inferenceId instanceof Literal && DataType.isString(inferenceId.dataType())) == false) { throw new ParsingException( inferenceId.source(), "Option [{}] must be a valid string, found [{}]", Completion.INFERENCE_ID_OPTION_NAME, inferenceId.source().text() ); } return inferencePlan.withInferenceId(inferenceId); } public PlanFactory visitSampleCommand(EsqlBaseParser.SampleCommandContext ctx) { Source source = source(ctx); Object val = expression(ctx.probability).fold(FoldContext.small() /* TODO remove me */); if (val instanceof Double probability && probability > 0.0 && probability < 1.0) { return input -> new Sample(source, new Literal(source, probability, DataType.DOUBLE), input); } else { throw new ParsingException( source(ctx), "invalid value for SAMPLE probability [" + BytesRefs.toString(val) + "], expecting a number between 0 and 1, exclusive" ); } } @Override public PlanFactory visitPromqlCommand(EsqlBaseParser.PromqlCommandContext ctx) { Source source = source(ctx); // Check if PromQL functionality is enabled if (PromqlFeatures.isEnabled() == false) { throw new ParsingException( source, "PROMQL command is not available. Requires snapshot build with capability [promql_vX] enabled" ); } PromqlParams params = parsePromqlParams(ctx, source); // TODO: Perform type and value validation var queryCtx = ctx.promqlQueryPart(); if (queryCtx == null || queryCtx.isEmpty()) { throw new ParsingException(source, "PromQL expression cannot be empty"); } Token startToken = queryCtx.getFirst().start; Token stopToken = queryCtx.getLast().stop; // copy the query verbatim to avoid missing tokens interpreted by the enclosing lexer String promqlQuery = source(startToken, stopToken).text(); if (promqlQuery.isBlank()) { throw new ParsingException(source, "PromQL expression cannot be empty"); } int promqlStartLine = startToken.getLine(); int promqlStartColumn = startToken.getCharPositionInLine(); PromqlParser promqlParser = new PromqlParser(); LogicalPlan promqlPlan; try { // The existing PromqlParser is used to parse the inner query promqlPlan = promqlParser.createStatement( promqlQuery, params.startLiteral(), params.endLiteral(), promqlStartLine, promqlStartColumn ); } catch (ParsingException pe) { throw PromqlParserUtils.adjustParsingException(pe, promqlStartLine, promqlStartColumn); } return plan -> new PromqlCommand( source, plan, promqlPlan, params.startLiteral(), params.endLiteral(), params.stepLiteral(), new UnresolvedTimestamp(source) ); } private PromqlParams parsePromqlParams(EsqlBaseParser.PromqlCommandContext ctx, Source source) { Instant time = null; Instant start = null; Instant end = null; Duration step = null; Set<String> paramsSeen = new HashSet<>(); for (EsqlBaseParser.PromqlParamContext paramCtx : ctx.promqlParam()) { var paramNameCtx = paramCtx.name; String name = parseParamName(paramCtx.name); if (paramsSeen.add(name) == false) { throw new ParsingException(source(paramNameCtx), "[{}] already specified", name); } Source valueSource = source(paramCtx.value); String valueString = parseParamValue(paramCtx.value); switch (name) { case TIME -> time = PromqlParserUtils.parseDate(valueSource, valueString); case START -> start = PromqlParserUtils.parseDate(valueSource, valueString); case END -> end = PromqlParserUtils.parseDate(valueSource, valueString); case STEP -> { try { step = Duration.ofSeconds(Integer.parseInt(valueString)); } catch (NumberFormatException ignore) { step = PromqlParserUtils.parseDuration(valueSource, valueString); } } default -> { String message = "Unknown parameter [{}]"; List<String> similar = StringUtils.findSimilar(name, PROMQL_ALLOWED_PARAMS); if (CollectionUtils.isEmpty(similar) == false) { message += ", did you mean " + (similar.size() == 1 ? "[" + similar.get(0) + "]" : "any of " + similar) + "?"; } throw new ParsingException(source(paramNameCtx), message, name); } } } // Validation logic for time parameters if (time != null) { if (start != null || end != null || step != null) { throw new ParsingException( source, "Specify either [{}] for instant query or [{}], [{}] or [{}] for a range query", TIME, STEP, START, END ); } start = time; end = time; } else if (step != null) { if (start != null || end != null) { if (start == null || end == null) { throw new ParsingException( source, "Parameters [{}] and [{}] must either both be specified or both be omitted for a range query", START, END ); } if (end.isBefore(start)) { throw new ParsingException( source, "invalid parameter \"end\": end timestamp must not be before start time", end, start ); } } if (step.isPositive() == false) { throw new ParsingException( source, "invalid parameter \"step\": zero or negative query resolution step widths are not accepted. " + "Try a positive integer", step ); } } else { throw new ParsingException(source, "Parameter [{}] or [{}] is required", STEP, TIME); } return new PromqlParams(source, start, end, step); } private String parseParamName(EsqlBaseParser.PromqlParamContentContext ctx) { if (ctx.PROMQL_UNQUOTED_IDENTIFIER() != null) { return ctx.PROMQL_UNQUOTED_IDENTIFIER().getText(); } else if (ctx.QUOTED_IDENTIFIER() != null) { return AbstractBuilder.unquote(ctx.QUOTED_IDENTIFIER().getText()); } else { throw new ParsingException(source(ctx), "Parameter name [{}] must be an identifier", ctx.getText()); } } private String parseParamValue(EsqlBaseParser.PromqlParamContentContext ctx) { if (ctx.PROMQL_UNQUOTED_IDENTIFIER() != null) { return ctx.PROMQL_UNQUOTED_IDENTIFIER().getText(); } else if (ctx.QUOTED_STRING() != null) { return AbstractBuilder.unquote(ctx.QUOTED_STRING().getText()); } else if (ctx.NAMED_OR_POSITIONAL_PARAM() != null) { QueryParam param = paramByNameOrPosition(ctx.NAMED_OR_POSITIONAL_PARAM()); return param.value().toString(); } else if (ctx.QUOTED_IDENTIFIER() != null) { throw new ParsingException(source(ctx), "Parameter value [{}] must not be a quoted identifier", ctx.getText()); } else { throw new ParsingException(source(ctx), "Invalid parameter value [{}]", ctx.getText()); } } /** * Container for PromQL command parameters: * <ul> * <li>time for instant queries</li> * <li>start, end, step for range queries</li> * </ul> * These can be specified in the {@linkplain PromqlCommand PROMQL command} like so: * <pre> * # instant query * PROMQL time "2025-10-31T00:00:00Z" (avg(foo)) * # range query with explicit start and end * PROMQL start "2025-10-31T00:00:00Z" end "2025-10-31T01:00:00Z" step 1m (avg(foo)) * # range query with implicit time bounds, doesn't support calling {@code start()} or {@code end()} functions * PROMQL step 5m (avg(foo)) * </pre> * * @see <a href="https://prometheus.io/docs/prometheus/latest/querying/api/#expression-queries">PromQL API documentation</a> */ public record PromqlParams(Source source, Instant start, Instant end, Duration step) { public Literal startLiteral() { if (start == null) { return Literal.NULL; } return Literal.dateTime(source, start); } public Literal endLiteral() { if (end == null) { return Literal.NULL; } return Literal.dateTime(source, end); } public Literal stepLiteral() { if (step == null) { return Literal.NULL; } return Literal.timeDuration(source, step); } } }
LogicalPlanBuilder
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/typesafe/TypeSafeLetTest.java
{ "start": 365, "end": 1101 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(Movie.class) .addAsResource(new StringAsset("{@io.quarkus.qute.deployment.typesafe.Movie movie}" + "{#let service=movie.findService('foo') name?=movie.name}" + "{service.shortValue}" + "::{name.length}" + "{/let}"), "templates/foo.html")); @Inject Template foo; @Test public void testValidation() { assertEquals("10::5", foo.data("movie", new Movie()).render()); } }
TypeSafeLetTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/OneInputStreamOperator.java
{ "start": 1122, "end": 1299 }
class ____ you want to * implement a custom operator. * * @param <IN> The input type of the operator * @param <OUT> The output type of the operator */ @PublicEvolving public
if
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxInputStream.java
{ "start": 11291, "end": 11366 }
enum ____ { NONE, REQUIRED, SENT; } }
ContinueState
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerManyToOne3Test.java
{ "start": 1050, "end": 2869 }
class ____ { @AfterEach public void tearDown(EntityManagerFactoryScope scope) { scope.getEntityManagerFactory().getSchemaManager().truncate(); } @Test public void testFindParent(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { Parent parent = new Parent( 1l, "Fab" ); Child child = new Child( 2l, new Date() ); parent.addChild( child ); entityManager.persist( parent ); } ); scope.inTransaction( entityManager -> { Parent parent = entityManager.find( Parent.class, 1 ); assertThat( parent ).isNotNull(); assertThat( parent.children.size() ).isEqualTo( 0 ); } ); scope.inTransaction( entityManager -> { List<Child> children = entityManager.createQuery( "select c from Child c", Child.class ) .getResultList(); assertThat( children.size() ).isEqualTo( 0 ); } ); } @Test public void testFindParent2(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { Parent parent = new Parent( 1l, "Fab" ); Child child = new Child( 2l, new Date() ); Child child2 = new Child( 3l, null ); parent.addChild( child ); parent.addChild( child2 ); entityManager.persist( parent ); } ); scope.inTransaction( entityManager -> { Parent parent = entityManager.find( Parent.class, 1 ); assertThat( parent ).isNotNull(); assertThat( parent.children.size() ).isEqualTo( 1 ); } ); scope.inTransaction( entityManager -> { List<Child> children = entityManager.createQuery( "select c from Child c", Child.class ) .getResultList(); assertThat( children.size() ).isEqualTo( 1 ); } ); } @Entity(name = "Child") @Table(name = "children") @SQLRestriction("deleted_at IS NULL") public static
EagerManyToOne3Test
java
google__guava
android/guava/src/com/google/common/hash/Funnels.java
{ "start": 3655, "end": 4202 }
class ____ implements Serializable { private final String charsetCanonicalName; SerializedForm(Charset charset) { this.charsetCanonicalName = charset.name(); } private Object readResolve() { return stringFunnel(Charset.forName(charsetCanonicalName)); } private static final long serialVersionUID = 0; } } /** * Returns a funnel for integers. * * @since 13.0 */ public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private
SerializedForm
java
apache__kafka
storage/src/test/java/org/apache/kafka/server/log/remote/storage/RemoteLogOffsetReaderTest.java
{ "start": 2427, "end": 6639 }
class ____ { private final MockTime time = new MockTime(); private final TopicPartition topicPartition = new TopicPartition("test", 0); private Path logDir; private LeaderEpochFileCache cache; private MockRemoteLogManager rlm; @BeforeEach void setUp() throws IOException { logDir = Files.createTempDirectory("kafka-test"); LeaderEpochCheckpointFile checkpoint = new LeaderEpochCheckpointFile(TestUtils.tempFile(), new LogDirFailureChannel(1)); cache = new LeaderEpochFileCache(topicPartition, checkpoint, time.scheduler); rlm = new MockRemoteLogManager(2, 1, logDir.toString()); } @AfterEach void tearDown() throws IOException { rlm.close(); Utils.delete(logDir.toFile()); } @Test public void testReadRemoteLog() throws Exception { AsyncOffsetReadFutureHolder<OffsetResultHolder.FileRecordsOrError> asyncOffsetReadFutureHolder = rlm.asyncOffsetRead(topicPartition, time.milliseconds(), 0L, cache, Optional::empty); asyncOffsetReadFutureHolder.taskFuture().get(1, TimeUnit.SECONDS); assertTrue(asyncOffsetReadFutureHolder.taskFuture().isDone()); OffsetResultHolder.FileRecordsOrError result = asyncOffsetReadFutureHolder.taskFuture().get(); assertFalse(result.hasException()); assertTrue(result.hasTimestampAndOffset()); assertEquals(new TimestampAndOffset(100L, 90L, Optional.of(3)), result.timestampAndOffset().get()); } @Test public void testTaskQueueFullAndCancelTask() throws Exception { rlm.pause(); List<AsyncOffsetReadFutureHolder<OffsetResultHolder.FileRecordsOrError>> holderList = new ArrayList<>(); // Task queue size is 1 and number of threads is 2, so it can accept at-most 3 items for (int i = 0; i < 3; i++) { holderList.add(rlm.asyncOffsetRead(topicPartition, time.milliseconds(), 0L, cache, Optional::empty)); } assertThrows(TimeoutException.class, () -> holderList.get(0).taskFuture().get(10, TimeUnit.MILLISECONDS)); assertEquals(0, holderList.stream().filter(h -> h.taskFuture().isDone()).count()); assertThrows(RejectedExecutionException.class, () -> holderList.add(rlm.asyncOffsetRead(topicPartition, time.milliseconds(), 0L, cache, Optional::empty))); holderList.get(2).jobFuture().cancel(false); rlm.resume(); for (AsyncOffsetReadFutureHolder<OffsetResultHolder.FileRecordsOrError> holder : holderList) { if (!holder.jobFuture().isCancelled()) { holder.taskFuture().get(1, TimeUnit.SECONDS); } } assertEquals(3, holderList.size()); assertEquals(2, holderList.stream().filter(h -> h.taskFuture().isDone()).count()); assertEquals(1, holderList.stream().filter(h -> !h.taskFuture().isDone()).count()); } @Test public void testThrowErrorOnFindOffsetByTimestamp() throws Exception { RemoteStorageException exception = new RemoteStorageException("Error"); try (RemoteLogManager rlm = new MockRemoteLogManager(2, 1, logDir.toString()) { @Override public Optional<TimestampAndOffset> findOffsetByTimestamp(TopicPartition tp, long timestamp, long startingOffset, LeaderEpochFileCache leaderEpochCache) throws RemoteStorageException { throw exception; } }) { AsyncOffsetReadFutureHolder<OffsetResultHolder.FileRecordsOrError> futureHolder = rlm.asyncOffsetRead(topicPartition, time.milliseconds(), 0L, cache, Optional::empty); futureHolder.taskFuture().get(1, TimeUnit.SECONDS); assertTrue(futureHolder.taskFuture().isDone()); assertTrue(futureHolder.taskFuture().get().hasException()); assertEquals(exception, futureHolder.taskFuture().get().exception().get()); } } private static
RemoteLogOffsetReaderTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/session/IndexResolver.java
{ "start": 25949, "end": 26225 }
interface ____ { Map<String, List<String>> apply(String indexPattern, FieldCapabilitiesResponse fieldCapabilitiesResponse); } public static final OriginalIndexExtractor DO_NOT_GROUP = (indexPattern, fieldCapabilitiesResponse) -> Map.of(); }
OriginalIndexExtractor
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/AbstractMethodMessageHandler.java
{ "start": 3011, "end": 9682 }
class ____<T> implements MessageHandler, ApplicationContextAware, InitializingBean { /** * Bean name prefix for target beans behind scoped proxies. Used to exclude those * targets from handler method detection, in favor of the corresponding proxies. * <p>We're not checking the autowire-candidate status here, which is how the * proxy target filtering problem is being handled at the autowiring level, * since autowire-candidate may have been turned to {@code false} for other * reasons, while still expecting the bean to be eligible for handler methods. * <p>Originally defined in {@link org.springframework.aop.scope.ScopedProxyUtils} * but duplicated here to avoid a hard dependency on the spring-aop module. */ private static final String SCOPED_TARGET_NAME_PREFIX = "scopedTarget."; protected final Log logger = LogFactory.getLog(getClass()); private @Nullable Log handlerMethodLogger; private final List<String> destinationPrefixes = new ArrayList<>(); private final List<HandlerMethodArgumentResolver> customArgumentResolvers = new ArrayList<>(4); private final List<HandlerMethodReturnValueHandler> customReturnValueHandlers = new ArrayList<>(4); private final HandlerMethodArgumentResolverComposite argumentResolvers = new HandlerMethodArgumentResolverComposite(); private final HandlerMethodReturnValueHandlerComposite returnValueHandlers = new HandlerMethodReturnValueHandlerComposite(); private @Nullable ApplicationContext applicationContext; private final Map<T, HandlerMethod> handlerMethods = new LinkedHashMap<>(64); private final MultiValueMap<String, T> destinationLookup = new LinkedMultiValueMap<>(48); private final Map<Class<?>, AbstractExceptionHandlerMethodResolver> exceptionHandlerCache = new ConcurrentHashMap<>(64); private final Map<MessagingAdviceBean, AbstractExceptionHandlerMethodResolver> exceptionHandlerAdviceCache = new LinkedHashMap<>(64); /** * When this property is configured only messages to destinations matching * one of the configured prefixes are eligible for handling. When there is a * match the prefix is removed and only the remaining part of the destination * is used for method-mapping purposes. * <p>By default, no prefixes are configured in which case all messages are * eligible for handling. */ public void setDestinationPrefixes(@Nullable Collection<String> prefixes) { this.destinationPrefixes.clear(); if (prefixes != null) { for (String prefix : prefixes) { prefix = prefix.trim(); this.destinationPrefixes.add(prefix); } } } /** * Return the configured destination prefixes, if any. */ public Collection<String> getDestinationPrefixes() { return this.destinationPrefixes; } /** * Sets the list of custom {@code HandlerMethodArgumentResolver}s that will be used * after resolvers for supported argument type. */ public void setCustomArgumentResolvers(@Nullable List<HandlerMethodArgumentResolver> customArgumentResolvers) { this.customArgumentResolvers.clear(); if (customArgumentResolvers != null) { this.customArgumentResolvers.addAll(customArgumentResolvers); } } /** * Return the configured custom argument resolvers, if any. */ public List<HandlerMethodArgumentResolver> getCustomArgumentResolvers() { return this.customArgumentResolvers; } /** * Set the list of custom {@code HandlerMethodReturnValueHandler}s that will be used * after return value handlers for known types. */ public void setCustomReturnValueHandlers(@Nullable List<HandlerMethodReturnValueHandler> customReturnValueHandlers) { this.customReturnValueHandlers.clear(); if (customReturnValueHandlers != null) { this.customReturnValueHandlers.addAll(customReturnValueHandlers); } } /** * Return the configured custom return value handlers, if any. */ public List<HandlerMethodReturnValueHandler> getCustomReturnValueHandlers() { return this.customReturnValueHandlers; } /** * Configure the complete list of supported argument types, effectively overriding * the ones configured by default. This is an advanced option; for most use cases * it should be sufficient to use {@link #setCustomArgumentResolvers}. */ public void setArgumentResolvers(@Nullable List<HandlerMethodArgumentResolver> argumentResolvers) { if (argumentResolvers == null) { this.argumentResolvers.clear(); return; } this.argumentResolvers.addResolvers(argumentResolvers); } /** * Return the complete list of argument resolvers. */ public List<HandlerMethodArgumentResolver> getArgumentResolvers() { return this.argumentResolvers.getResolvers(); } /** * Configure the complete list of supported return value types, effectively overriding * the ones configured by default. This is an advanced option; for most use cases * it should be sufficient to use {@link #setCustomReturnValueHandlers}. */ public void setReturnValueHandlers(@Nullable List<HandlerMethodReturnValueHandler> returnValueHandlers) { if (returnValueHandlers == null) { this.returnValueHandlers.clear(); return; } this.returnValueHandlers.addHandlers(returnValueHandlers); } /** * Return the complete list of return value handlers. */ public List<HandlerMethodReturnValueHandler> getReturnValueHandlers() { return this.returnValueHandlers.getReturnValueHandlers(); } @Override public void setApplicationContext(@Nullable ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public @Nullable ApplicationContext getApplicationContext() { return this.applicationContext; } @Override public void afterPropertiesSet() { if (this.argumentResolvers.getResolvers().isEmpty()) { this.argumentResolvers.addResolvers(initArgumentResolvers()); } if (this.returnValueHandlers.getReturnValueHandlers().isEmpty()) { this.returnValueHandlers.addHandlers(initReturnValueHandlers()); } Log returnValueLogger = getReturnValueHandlerLogger(); if (returnValueLogger != null) { this.returnValueHandlers.setLogger(returnValueLogger); } this.handlerMethodLogger = getHandlerMethodLogger(); ApplicationContext context = getApplicationContext(); if (context == null) { return; } for (String beanName : context.getBeanNamesForType(Object.class)) { if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) { Class<?> beanType = null; try { beanType = context.getType(beanName); } catch (Throwable ex) { // An unresolvable bean type, probably from a lazy bean - let's ignore it. if (logger.isDebugEnabled()) { logger.debug("Could not resolve target
AbstractMethodMessageHandler
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/rule/RuleExecutor.java
{ "start": 690, "end": 1775 }
class ____<TreeType extends Node<TreeType>> { private final Logger log = LogManager.getLogger(getClass()); /** * Sub-logger intended to show only changes made by the rules. Intended for debugging. * * Enable it like this for the respective optimizers and the analyzer, resp. all inheritors of this class: * <pre>{@code * PUT localhost:9200/_cluster/settings * * { * "transient" : { * "logger.org.elasticsearch.xpack.esql.analysis.Analyzer.changes": "TRACE", * "logger.org.elasticsearch.xpack.esql.optimizer.LogicalPlanOptimizer.changes": "TRACE", * "logger.org.elasticsearch.xpack.esql.optimizer.LocalLogicalPlanOptimizer.changes": "TRACE", * "logger.org.elasticsearch.xpack.esql.optimizer.PhysicalPlanOptimizer.changes": "TRACE", * "logger.org.elasticsearch.xpack.esql.optimizer.LocalPhysicalPlanOptimizer.changes": "TRACE" * } * } * }</pre> */ private final Logger changeLog = LogManager.getLogger(getClass().getName() + ".changes"); public static
RuleExecutor
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptivebatch/StreamGraphOptimizationStrategy.java
{ "start": 1320, "end": 1761 }
interface ____ { @Internal ConfigOption<List<String>> STREAM_GRAPH_OPTIMIZATION_STRATEGY = ConfigOptions.key("execution.batch.adaptive.stream-graph-optimization.strategies") .stringType() .asList() .noDefaultValue() .withDescription( "Defines a comma-separated list of fully qualified
StreamGraphOptimizationStrategy
java
quarkusio__quarkus
extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/graal/FeatureDetectorSubstitutions.java
{ "start": 258, "end": 1098 }
class ____ { @Substitute public FeatureDetectorSubstitutions(ClassLoader classLoader) { } @Substitute public boolean isApacheCommonsLoggingAvailable() { return false; } @Substitute public boolean isSlf4jAvailable() { return false; } @Substitute public boolean isJBossVFSv2Available() { return false; } @Substitute public boolean isJBossVFSv3Available() { return false; } @Substitute public boolean isOsgiFrameworkAvailable() { return false; } @Substitute public boolean isLog4J2Available() { return false; } @Substitute public boolean isAwsAvailable() { return false; } @Substitute public boolean isGCSAvailable() { return false; } }
FeatureDetectorSubstitutions
java
apache__camel
components/camel-spring-parent/camel-spring-rabbitmq/src/generated/java/org/apache/camel/component/springrabbit/SpringRabbitMQEndpointUriFactory.java
{ "start": 522, "end": 3787 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":exchangeName"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(42); props.add("acknowledgeMode"); props.add("allowNullBody"); props.add("args"); props.add("asyncConsumer"); props.add("autoDeclare"); props.add("autoDeclareProducer"); props.add("autoStartup"); props.add("bridgeErrorHandler"); props.add("concurrentConsumers"); props.add("confirm"); props.add("confirmTimeout"); props.add("connectionFactory"); props.add("deadLetterExchange"); props.add("deadLetterExchangeType"); props.add("deadLetterQueue"); props.add("deadLetterRoutingKey"); props.add("disableReplyTo"); props.add("exceptionHandler"); props.add("exchangeName"); props.add("exchangePattern"); props.add("exchangeType"); props.add("exclusive"); props.add("lazyStartProducer"); props.add("maxConcurrentConsumers"); props.add("maximumRetryAttempts"); props.add("messageConverter"); props.add("messageListenerContainerType"); props.add("messagePropertiesConverter"); props.add("noLocal"); props.add("prefetchCount"); props.add("queues"); props.add("rejectAndDontRequeue"); props.add("replyTimeout"); props.add("retry"); props.add("retryDelay"); props.add("routingKey"); props.add("skipBindQueue"); props.add("skipDeclareExchange"); props.add("skipDeclareQueue"); props.add("synchronous"); props.add("testConnectionOnStartup"); props.add("usePublisherConnection"); PROPERTY_NAMES = Collections.unmodifiableSet(props); SECRET_PROPERTY_NAMES = Collections.emptySet(); Map<String, String> prefixes = new HashMap<>(1); prefixes.put("args", "arg."); MULTI_VALUE_PREFIXES = Collections.unmodifiableMap(prefixes); } @Override public boolean isEnabled(String scheme) { return "spring-rabbitmq".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "exchangeName", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
SpringRabbitMQEndpointUriFactory
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractCoordinator.java
{ "start": 73061, "end": 80086 }
class ____ extends BaseHeartbeatThread { private HeartbeatThread() { super(HEARTBEAT_THREAD_PREFIX + (rebalanceConfig.groupId.isEmpty() ? "" : " | " + rebalanceConfig.groupId), true); } @Override public void enable() { synchronized (AbstractCoordinator.this) { log.debug("Enabling heartbeat thread"); super.enable(); heartbeat.resetTimeouts(); AbstractCoordinator.this.notify(); } } @Override public void close() { synchronized (AbstractCoordinator.this) { super.close(); AbstractCoordinator.this.notify(); } } @Override public void run() { try { log.debug("Heartbeat thread started"); while (true) { synchronized (AbstractCoordinator.this) { if (isClosed()) return; if (!isEnabled()) { AbstractCoordinator.this.wait(); continue; } // we do not need to heartbeat we are not part of a group yet; // also if we already have fatal error, the client will be // crashed soon, hence we do not need to continue heartbeating either if (state.hasNotJoinedGroup() || isFailed()) { disable(); continue; } client.pollNoWakeup(); long now = time.milliseconds(); if (coordinatorUnknown()) { if (findCoordinatorFuture != null) { // clear the future so that after the backoff, if the hb still sees coordinator unknown in // the next iteration it will try to re-discover the coordinator in case the main thread cannot clearFindCoordinatorFuture(); } else { lookupCoordinator(); } // backoff properly AbstractCoordinator.this.wait(rebalanceConfig.retryBackoffMs); } else if (heartbeat.sessionTimeoutExpired(now)) { // the session timeout has expired without seeing a successful heartbeat, so we should // probably make sure the coordinator is still healthy. markCoordinatorUnknown("session timed out without receiving a " + "heartbeat response"); } else if (heartbeat.pollTimeoutExpired(now)) { // the poll timeout has expired, which means that the foreground thread has stalled // in between calls to poll(). handlePollTimeoutExpiry(); } else if (!heartbeat.shouldHeartbeat(now)) { // poll again after waiting for the retry backoff in case the heartbeat failed or the // coordinator disconnected. Note that the heartbeat timing takes account of // exponential backoff. AbstractCoordinator.this.wait(rebalanceConfig.retryBackoffMs); } else { heartbeat.sentHeartbeat(now); final RequestFuture<Void> heartbeatFuture = sendHeartbeatRequest(); heartbeatFuture.addListener(new RequestFutureListener<>() { @Override public void onSuccess(Void value) { synchronized (AbstractCoordinator.this) { heartbeat.receiveHeartbeat(); } } @Override public void onFailure(RuntimeException e) { synchronized (AbstractCoordinator.this) { if (e instanceof RebalanceInProgressException) { // it is valid to continue heartbeating while the group is rebalancing. This // ensures that the coordinator keeps the member in the group for as long // as the duration of the rebalance timeout. If we stop sending heartbeats, // however, then the session timeout may expire before we can rejoin. heartbeat.receiveHeartbeat(); } else if (e instanceof FencedInstanceIdException) { log.error("Caught fenced group.instance.id {} error in heartbeat thread", rebalanceConfig.groupInstanceId); setFailureCause(e); } else { heartbeat.failHeartbeat(); // wake up the thread if it's sleeping to reschedule the heartbeat AbstractCoordinator.this.notify(); } } } }); } } } } catch (AuthenticationException e) { log.error("An authentication error occurred in the heartbeat thread", e); setFailureCause(e); } catch (GroupAuthorizationException e) { log.error("A group authorization error occurred in the heartbeat thread", e); setFailureCause(e); } catch (InterruptedException | InterruptException e) { Thread.interrupted(); log.error("Unexpected interrupt received in heartbeat thread", e); setFailureCause(new RuntimeException(e)); } catch (Throwable e) { log.error("Heartbeat thread failed due to unexpected error", e); if (e instanceof RuntimeException) setFailureCause((RuntimeException) e); else setFailureCause(new RuntimeException(e)); } finally { log.debug("Heartbeat thread has closed"); synchronized (AbstractCoordinator.this) { super.close(); } } } } protected static
HeartbeatThread
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/util/JvmUtils.java
{ "start": 1374, "end": 4225 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(JvmUtils.class); /** * Creates a thread dump of the current JVM. * * @return the thread dump of current JVM */ public static Collection<ThreadInfo> createThreadDump() { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); return Arrays.asList(threadMxBean.dumpAllThreads(true, true)); } /** * Creates a {@link ThreadInfoSample} for a specific thread. Contains thread traces if * maxStackTraceDepth > 0. * * @param threadId The ID of the thread to create the thread dump for. * @param maxStackTraceDepth The maximum number of entries in the stack trace to be collected. * @return The thread information of a specific thread. */ public static Optional<ThreadInfoSample> createThreadInfoSample( long threadId, int maxStackTraceDepth) { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); return ThreadInfoSample.from(threadMxBean.getThreadInfo(threadId, maxStackTraceDepth)); } /** * Creates a {@link ThreadInfoSample} for a specific thread. Contains thread traces if * maxStackTraceDepth > 0. * * @param threadIds The IDs of the threads to create the thread dump for. * @param maxStackTraceDepth The maximum number of entries in the stack trace to be collected. * @return The map key is the thread id, the map value is the thread information for the * requested thread IDs. */ public static Map<Long, ThreadInfoSample> createThreadInfoSample( Collection<Long> threadIds, int maxStackTraceDepth) { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); long[] threadIdsArray = threadIds.stream().mapToLong(l -> l).toArray(); ThreadInfo[] threadInfo = threadMxBean.getThreadInfo(threadIdsArray, maxStackTraceDepth); List<ThreadInfo> threadInfoNoNulls = IntStream.range(0, threadIdsArray.length) .filter( i -> { if (threadInfo[i] == null) { LOG.debug( "FlameGraphs: thread {} is not alive or does not exist.", threadIdsArray[i]); return false; } return true; }) .mapToObj(i -> threadInfo[i]) .collect(Collectors.toList()); return ThreadInfoSample.from(threadInfoNoNulls); } /** Private default constructor to avoid instantiation. */ private JvmUtils() {} }
JvmUtils
java
apache__camel
components/camel-dhis2/camel-dhis2-component/src/generated/java/org/apache/camel/component/dhis2/internal/Dhis2PutApiMethod.java
{ "start": 657, "end": 1634 }
enum ____ implements ApiMethod { RESOURCE( java.io.InputStream.class, "resource", arg("path", String.class), arg("resource", Object.class), arg("queryParams", java.util.Map.class)); private final ApiMethod apiMethod; Dhis2PutApiMethod(Class<?> resultType, String name, ApiMethodArg... args) { this.apiMethod = new ApiMethodImpl(Dhis2Put.class, resultType, name, args); } @Override public String getName() { return apiMethod.getName(); } @Override public Class<?> getResultType() { return apiMethod.getResultType(); } @Override public List<String> getArgNames() { return apiMethod.getArgNames(); } @Override public List<String> getSetterArgNames() { return apiMethod.getSetterArgNames(); } @Override public List<Class<?>> getArgTypes() { return apiMethod.getArgTypes(); } @Override public Method getMethod() { return apiMethod.getMethod(); } }
Dhis2PutApiMethod
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/transformer/ArgumentTransformerTest.java
{ "start": 2575, "end": 2933 }
class ____ { public String hello(int param1, List<String> param2) { return "foobar" + param1 + param2; } public Set<String> doSomething(String param) { return Set.of("quux", param); } public long increment(double param) { return (long) param + 1; } } static
MyService
java
quarkusio__quarkus
independent-projects/tools/devtools-common/src/main/java/io/quarkus/maven/utilities/MojoUtils.java
{ "start": 10281, "end": 10537 }
class ____ { private List<Attribute> attributes; public Attributes(Attribute... attributes) { this.attributes = Arrays.asList(attributes); } } /** * Attribute wrapper class */ public static
Attributes
java
apache__camel
components/camel-ai/camel-torchserve/src/generated/java/org/apache/camel/component/torchserve/TorchServeEndpointConfigurer.java
{ "start": 737, "end": 8513 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { TorchServeEndpoint target = (TorchServeEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "inferenceaddress": case "inferenceAddress": target.getConfiguration().setInferenceAddress(property(camelContext, java.lang.String.class, value)); return true; case "inferencekey": case "inferenceKey": target.getConfiguration().setInferenceKey(property(camelContext, java.lang.String.class, value)); return true; case "inferenceport": case "inferencePort": target.getConfiguration().setInferencePort(property(camelContext, int.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "listlimit": case "listLimit": target.getConfiguration().setListLimit(property(camelContext, int.class, value)); return true; case "listnextpagetoken": case "listNextPageToken": target.getConfiguration().setListNextPageToken(property(camelContext, java.lang.String.class, value)); return true; case "managementaddress": case "managementAddress": target.getConfiguration().setManagementAddress(property(camelContext, java.lang.String.class, value)); return true; case "managementkey": case "managementKey": target.getConfiguration().setManagementKey(property(camelContext, java.lang.String.class, value)); return true; case "managementport": case "managementPort": target.getConfiguration().setManagementPort(property(camelContext, int.class, value)); return true; case "metricsaddress": case "metricsAddress": target.getConfiguration().setMetricsAddress(property(camelContext, java.lang.String.class, value)); return true; case "metricsname": case "metricsName": target.getConfiguration().setMetricsName(property(camelContext, java.lang.String.class, value)); return true; case "metricsport": case "metricsPort": target.getConfiguration().setMetricsPort(property(camelContext, int.class, value)); return true; case "modelname": case "modelName": target.getConfiguration().setModelName(property(camelContext, java.lang.String.class, value)); return true; case "modelversion": case "modelVersion": target.getConfiguration().setModelVersion(property(camelContext, java.lang.String.class, value)); return true; case "registeroptions": case "registerOptions": target.getConfiguration().setRegisterOptions(property(camelContext, org.apache.camel.component.torchserve.client.model.RegisterOptions.class, value)); return true; case "scaleworkeroptions": case "scaleWorkerOptions": target.getConfiguration().setScaleWorkerOptions(property(camelContext, org.apache.camel.component.torchserve.client.model.ScaleWorkerOptions.class, value)); return true; case "unregisteroptions": case "unregisterOptions": target.getConfiguration().setUnregisterOptions(property(camelContext, org.apache.camel.component.torchserve.client.model.UnregisterOptions.class, value)); return true; case "url": target.getConfiguration().setUrl(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "inferenceaddress": case "inferenceAddress": return java.lang.String.class; case "inferencekey": case "inferenceKey": return java.lang.String.class; case "inferenceport": case "inferencePort": return int.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "listlimit": case "listLimit": return int.class; case "listnextpagetoken": case "listNextPageToken": return java.lang.String.class; case "managementaddress": case "managementAddress": return java.lang.String.class; case "managementkey": case "managementKey": return java.lang.String.class; case "managementport": case "managementPort": return int.class; case "metricsaddress": case "metricsAddress": return java.lang.String.class; case "metricsname": case "metricsName": return java.lang.String.class; case "metricsport": case "metricsPort": return int.class; case "modelname": case "modelName": return java.lang.String.class; case "modelversion": case "modelVersion": return java.lang.String.class; case "registeroptions": case "registerOptions": return org.apache.camel.component.torchserve.client.model.RegisterOptions.class; case "scaleworkeroptions": case "scaleWorkerOptions": return org.apache.camel.component.torchserve.client.model.ScaleWorkerOptions.class; case "unregisteroptions": case "unregisterOptions": return org.apache.camel.component.torchserve.client.model.UnregisterOptions.class; case "url": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { TorchServeEndpoint target = (TorchServeEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "inferenceaddress": case "inferenceAddress": return target.getConfiguration().getInferenceAddress(); case "inferencekey": case "inferenceKey": return target.getConfiguration().getInferenceKey(); case "inferenceport": case "inferencePort": return target.getConfiguration().getInferencePort(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "listlimit": case "listLimit": return target.getConfiguration().getListLimit(); case "listnextpagetoken": case "listNextPageToken": return target.getConfiguration().getListNextPageToken(); case "managementaddress": case "managementAddress": return target.getConfiguration().getManagementAddress(); case "managementkey": case "managementKey": return target.getConfiguration().getManagementKey(); case "managementport": case "managementPort": return target.getConfiguration().getManagementPort(); case "metricsaddress": case "metricsAddress": return target.getConfiguration().getMetricsAddress(); case "metricsname": case "metricsName": return target.getConfiguration().getMetricsName(); case "metricsport": case "metricsPort": return target.getConfiguration().getMetricsPort(); case "modelname": case "modelName": return target.getConfiguration().getModelName(); case "modelversion": case "modelVersion": return target.getConfiguration().getModelVersion(); case "registeroptions": case "registerOptions": return target.getConfiguration().getRegisterOptions(); case "scaleworkeroptions": case "scaleWorkerOptions": return target.getConfiguration().getScaleWorkerOptions(); case "unregisteroptions": case "unregisterOptions": return target.getConfiguration().getUnregisterOptions(); case "url": return target.getConfiguration().getUrl(); default: return null; } } }
TorchServeEndpointConfigurer
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/util/IgnorePropertiesUtil.java
{ "start": 2750, "end": 2871 }
class ____ encapsulate logic from static {@code shouldIgnore} method * of util class. */ public final static
to
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/blockaliasmap/impl/TextFileRegionAliasMap.java
{ "start": 10139, "end": 12744 }
class ____ implements Iterator<FileRegion> { private FileRegion pending; @Override public boolean hasNext() { return pending != null; } @Override public FileRegion next() { if (null == pending) { throw new NoSuchElementException(); } FileRegion ret = pending; try { pending = nextInternal(this); } catch (IOException e) { throw new RuntimeException(e); } return ret; } @Override public void remove() { throw new UnsupportedOperationException(); } } private FileRegion nextInternal(Iterator<FileRegion> i) throws IOException { BufferedReader r = iterators.get(i); if (null == r) { throw new IllegalStateException(); } String line = r.readLine(); if (null == line) { iterators.remove(i); return null; } String[] f = line.split(delim); if (f.length != 5 && f.length != 6) { throw new IOException("Invalid line: " + line); } byte[] nonce = new byte[0]; if (f.length == 6) { nonce = Base64.getDecoder().decode(f[5]); } return new FileRegion(Long.parseLong(f[0]), new Path(f[1]), Long.parseLong(f[2]), Long.parseLong(f[3]), Long.parseLong(f[4]), nonce); } public InputStream createStream() throws IOException { InputStream i = fs.open(file); if (codec != null) { i = codec.createInputStream(i); } return i; } @Override public Iterator<FileRegion> iterator() { FRIterator i = new FRIterator(); try { BufferedReader r = new BufferedReader(new InputStreamReader(createStream(), StandardCharsets.UTF_8)); iterators.put(i, r); i.pending = nextInternal(i); } catch (IOException e) { iterators.remove(i); throw new RuntimeException(e); } return i; } @Override public void close() throws IOException { ArrayList<IOException> ex = new ArrayList<>(); synchronized (iterators) { for (Iterator<BufferedReader> i = iterators.values().iterator(); i.hasNext();) { try { BufferedReader r = i.next(); r.close(); } catch (IOException e) { ex.add(e); } finally { i.remove(); } } iterators.clear(); } if (!ex.isEmpty()) { throw MultipleIOException.createIOException(ex); } } } /** * This
FRIterator
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/streaming/HeadlineController.java
{ "start": 1052, "end": 1565 }
class ____ { // tag::streaming[] @Get(value = "/headlines", processes = MediaType.APPLICATION_JSON_STREAM) // <1> Publisher<Headline> streamHeadlines() { return Mono.fromCallable(() -> { // <2> Headline headline = new Headline(); headline.setText("Latest Headline at " + ZonedDateTime.now()); return headline; }).repeat(100) // <3> .delayElements(Duration.of(1, ChronoUnit.SECONDS)); // <4> } // end::streaming[] }
HeadlineController
java
apache__hadoop
hadoop-tools/hadoop-resourceestimator/src/main/java/org/apache/hadoop/resourceestimator/skylinestore/exceptions/NullPipelineIdException.java
{ "start": 964, "end": 1179 }
class ____ extends SkylineStoreException { private static final long serialVersionUID = -684069387367879218L; public NullPipelineIdException(final String message) { super(message); } }
NullPipelineIdException
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/physical/inference/RerankExec.java
{ "start": 1292, "end": 4350 }
class ____ extends InferenceExec { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry( PhysicalPlan.class, "RerankExec", RerankExec::new ); private final Expression queryText; private final List<Alias> rerankFields; private final Attribute scoreAttribute; private List<Attribute> lazyOutput; public RerankExec( Source source, PhysicalPlan child, Expression inferenceId, Expression queryText, List<Alias> rerankFields, Attribute scoreAttribute ) { super(source, child, inferenceId); this.queryText = queryText; this.rerankFields = rerankFields; this.scoreAttribute = scoreAttribute; } public RerankExec(StreamInput in) throws IOException { this( Source.readFrom((PlanStreamInput) in), in.readNamedWriteable(PhysicalPlan.class), in.readNamedWriteable(Expression.class), in.readNamedWriteable(Expression.class), in.readCollectionAsList(Alias::new), in.readNamedWriteable(Attribute.class) ); } public Expression queryText() { return queryText; } public List<Alias> rerankFields() { return rerankFields; } public Attribute scoreAttribute() { return scoreAttribute; } @Override public String getWriteableName() { return ENTRY.name; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeNamedWriteable(queryText()); out.writeCollection(rerankFields()); out.writeNamedWriteable(scoreAttribute); } @Override protected NodeInfo<? extends PhysicalPlan> info() { return NodeInfo.create(this, RerankExec::new, child(), inferenceId(), queryText, rerankFields, scoreAttribute); } @Override public UnaryExec replaceChild(PhysicalPlan newChild) { return new RerankExec(source(), newChild, inferenceId(), queryText, rerankFields, scoreAttribute); } @Override public List<Attribute> output() { if (lazyOutput == null) { lazyOutput = mergeOutputAttributes(List.of(scoreAttribute), child().output()); } return lazyOutput; } @Override protected AttributeSet computeReferences() { return Rerank.computeReferences(rerankFields); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (super.equals(o) == false) return false; RerankExec rerank = (RerankExec) o; return Objects.equals(queryText, rerank.queryText) && Objects.equals(rerankFields, rerank.rerankFields) && Objects.equals(scoreAttribute, rerank.scoreAttribute); } @Override public int hashCode() { return Objects.hash(super.hashCode(), queryText, rerankFields, scoreAttribute); } }
RerankExec
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingWithBidirectionalOneToOneFlushProblem.java
{ "start": 538, "end": 2991 }
class ____ extends BaseInsertOrderingTest { @Test public void testInsertSortingWithFlushPersistLeftBeforeRight() { sessionFactoryScope().inTransaction( session -> { TopEntity top1 = new TopEntity(); session.persist( top1 ); clearBatches(); session.flush(); verifyContainsBatches( new Batch( "insert into TopEntity (name,id) values (?,?)" ) ); LeftEntity left = new LeftEntity(); RightEntity right = new RightEntity(); TopEntity top2 = new TopEntity(); top1.lefts.add( left ); left.top = top1; top1.rights.add( right ); right.top = top1; // This one-to-one triggers the problem right.left = left; // If you persist right before left the problem goes away session.persist( left ); session.persist( right ); session.persist( top2 ); clearBatches(); } ); verifyContainsBatches( new Batch( "insert into TopEntity (name,id) values (?,?)" ), new Batch( "insert into LeftEntity (name,top_id,id) values (?,?,?)" ), new Batch( "insert into RightEntity (left_id,name,top_id,id) values (?,?,?,?)" ) ); } @Test public void testInsertSortingWithFlushPersistRightBeforeLeft() { sessionFactoryScope().inTransaction( session -> { TopEntity top1 = new TopEntity(); session.persist( top1 ); clearBatches(); session.flush(); verifyContainsBatches( new Batch( "insert into TopEntity (name,id) values (?,?)" ) ); LeftEntity left = new LeftEntity(); RightEntity right = new RightEntity(); TopEntity top2 = new TopEntity(); top1.lefts.add( left ); left.top = top1; top1.rights.add( right ); right.top = top1; // This one-to-one triggers the problem right.left = left; // If you persist right before left the problem goes away session.persist( right ); session.persist( left ); session.persist( top2 ); clearBatches(); } ); verifyContainsBatches( new Batch( "insert into TopEntity (name,id) values (?,?)" ), new Batch( "insert into LeftEntity (name,top_id,id) values (?,?,?)" ), new Batch( "insert into RightEntity (left_id,name,top_id,id) values (?,?,?,?)" ) ); } @Override protected Class<?>[] getAnnotatedClasses() { return new Class<?>[] { LeftEntity.class, RightEntity.class, TopEntity.class, }; } @Entity(name = "LeftEntity") public static
InsertOrderingWithBidirectionalOneToOneFlushProblem
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/errors/ServerErrorHandlerOnClientEndpointTest.java
{ "start": 568, "end": 1174 }
class ____ { @RegisterExtension public static final QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot(root -> { root.addClasses(Echo.class); }) .assertException(e -> { assertInstanceOf(WebSocketException.class, e); assertTrue(e.getMessage().contains( "@OnError callback on @WebSocketClient must not accept WebSocketConnection")); }); @Test void trigger() { } @WebSocketClient(path = "/echo") public static
ServerErrorHandlerOnClientEndpointTest
java
netty__netty
codec-http3/src/main/java/io/netty/handler/codec/http3/Http3FrameCodec.java
{ "start": 30011, "end": 32786 }
class ____ implements Runnable, GenericFutureListener<Future<? super QuicStreamChannel>> { private static final int STATE_SUSPENDED = 0b1000_0000; private static final int STATE_READ_PENDING = 0b0100_0000; private static final int STATE_READ_COMPLETE_PENDING = 0b0010_0000; private final ChannelHandlerContext ctx; private final Http3FrameCodec codec; private byte state; ReadResumptionListener(ChannelHandlerContext ctx, Http3FrameCodec codec) { this.ctx = ctx; this.codec = codec; assert codec.qpackAttributes != null; if (!codec.qpackAttributes.dynamicTableDisabled() && !codec.qpackAttributes.decoderStreamAvailable()) { codec.qpackAttributes.whenDecoderStreamAvailable(this); } } void suspended() { assert !codec.qpackAttributes.dynamicTableDisabled(); setState(STATE_SUSPENDED); } boolean readCompleted() { if (hasState(STATE_SUSPENDED)) { setState(STATE_READ_COMPLETE_PENDING); return false; } return true; } boolean readRequested() { if (hasState(STATE_SUSPENDED)) { setState(STATE_READ_PENDING); return false; } return true; } boolean isSuspended() { return hasState(STATE_SUSPENDED); } @Override public void operationComplete(Future<? super QuicStreamChannel> future) { if (future.isSuccess()) { resume(); } else { ctx.fireExceptionCaught(future.cause()); } } @Override public void run() { resume(); } private void resume() { unsetState(STATE_SUSPENDED); try { codec.channelRead(ctx, Unpooled.EMPTY_BUFFER); if (hasState(STATE_READ_COMPLETE_PENDING)) { unsetState(STATE_READ_COMPLETE_PENDING); codec.channelReadComplete(ctx); } if (hasState(STATE_READ_PENDING)) { unsetState(STATE_READ_PENDING); codec.read(ctx); } } catch (Exception e) { ctx.fireExceptionCaught(e); } } private void setState(int toSet) { state |= toSet; } private boolean hasState(int toCheck) { return (state & toCheck) == toCheck; } private void unsetState(int toUnset) { state &= ~toUnset; } } private static final
ReadResumptionListener
java
spring-projects__spring-framework
spring-beans/src/jmh/java/org/springframework/beans/BeanUtilsBenchmark.java
{ "start": 1739, "end": 1799 }
class ____ { } @SuppressWarnings("unused") static
TestClass1
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/TestMRAppComponentDependencies.java
{ "start": 1805, "end": 2514 }
class ____ { @Test @Timeout(value = 20) public void testComponentStopOrder() throws Exception { @SuppressWarnings("resource") TestMRApp app = new TestMRApp(1, 1, true, this.getClass().getName(), true); JobImpl job = (JobImpl) app.submit(new Configuration()); app.waitForState(job, JobState.SUCCEEDED); app.verifyCompleted(); int waitTime = 20 * 1000; while (waitTime > 0 && app.numStops < 2) { Thread.sleep(100); waitTime -= 100; } // assert JobHistoryEventHandlerStopped and then clientServiceStopped assertEquals(1, app.JobHistoryEventHandlerStopped); assertEquals(2, app.clientServiceStopped); } private final
TestMRAppComponentDependencies
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/dataframe/DataFrameAnalyticsConfigTests.java
{ "start": 3212, "end": 22607 }
class ____ extends AbstractBWCSerializationTestCase<DataFrameAnalyticsConfig> { @Override protected DataFrameAnalyticsConfig doParseInstance(XContentParser parser) throws IOException { ObjectParser<DataFrameAnalyticsConfig.Builder, Void> dataFrameAnalyticsConfigParser = lenient ? DataFrameAnalyticsConfig.LENIENT_PARSER : DataFrameAnalyticsConfig.STRICT_PARSER; return dataFrameAnalyticsConfigParser.apply(parser, null).build(); } @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { List<NamedWriteableRegistry.Entry> namedWriteables = new ArrayList<>(); namedWriteables.addAll(new MlDataFrameAnalysisNamedXContentProvider().getNamedWriteables()); namedWriteables.addAll(new MlInferenceNamedXContentProvider().getNamedWriteables()); namedWriteables.addAll(new SearchModule(Settings.EMPTY, Collections.emptyList()).getNamedWriteables()); return new NamedWriteableRegistry(namedWriteables); } @Override protected NamedXContentRegistry xContentRegistry() { List<NamedXContentRegistry.Entry> namedXContent = new ArrayList<>(); namedXContent.addAll(new MlDataFrameAnalysisNamedXContentProvider().getNamedXContentParsers()); namedXContent.addAll(new MlInferenceNamedXContentProvider().getNamedXContentParsers()); namedXContent.addAll(new SearchModule(Settings.EMPTY, Collections.emptyList()).getNamedXContents()); return new NamedXContentRegistry(namedXContent); } @Override protected DataFrameAnalyticsConfig createTestInstance() { return createRandom(randomValidId(), lenient); } @Override protected DataFrameAnalyticsConfig mutateInstance(DataFrameAnalyticsConfig instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected DataFrameAnalyticsConfig mutateInstanceForVersion(DataFrameAnalyticsConfig instance, TransportVersion version) { DataFrameAnalyticsConfig.Builder builder = new DataFrameAnalyticsConfig.Builder(instance).setSource( DataFrameAnalyticsSourceTests.mutateForVersion(instance.getSource(), version) ).setDest(DataFrameAnalyticsDestTests.mutateForVersion(instance.getDest(), version)); if (instance.getAnalysis() instanceof OutlierDetection) { builder.setAnalysis(OutlierDetectionTests.mutateForVersion((OutlierDetection) instance.getAnalysis(), version)); } if (instance.getAnalysis() instanceof Regression) { builder.setAnalysis(RegressionTests.mutateForVersion((Regression) instance.getAnalysis(), version)); } if (instance.getAnalysis() instanceof Classification) { builder.setAnalysis(ClassificationTests.mutateForVersion((Classification) instance.getAnalysis(), version)); } if (version.before(TransportVersions.V_8_8_0)) { builder.setMeta(null); } return builder.build(); } @Override protected Writeable.Reader<DataFrameAnalyticsConfig> instanceReader() { return DataFrameAnalyticsConfig::new; } public static DataFrameAnalyticsConfig createRandom(String id) { return createRandom(id, false); } public static DataFrameAnalyticsConfig createRandom(String id, boolean withGeneratedFields) { return createRandomBuilder( id, withGeneratedFields, randomFrom(OutlierDetectionTests.createRandom(), RegressionTests.createRandom(), ClassificationTests.createRandom()) ).build(); } public static DataFrameAnalyticsConfig.Builder createRandomBuilder(String id) { return createRandomBuilder( id, false, randomFrom(OutlierDetectionTests.createRandom(), RegressionTests.createRandom(), ClassificationTests.createRandom()) ); } public static DataFrameAnalyticsConfig.Builder createRandomBuilder(String id, boolean withGeneratedFields, DataFrameAnalysis analysis) { DataFrameAnalyticsSource source = DataFrameAnalyticsSourceTests.createRandom(); DataFrameAnalyticsDest dest = DataFrameAnalyticsDestTests.createRandom(); DataFrameAnalyticsConfig.Builder builder = new DataFrameAnalyticsConfig.Builder().setId(id) .setAnalysis(analysis) .setSource(source) .setDest(dest); if (randomBoolean()) { builder.setAnalyzedFields( FetchSourceContext.of( true, generateRandomStringArray(10, 10, false, false), generateRandomStringArray(10, 10, false, false) ) ); } if (randomBoolean()) { builder.setModelMemoryLimit(ByteSizeValue.of(randomIntBetween(1, 16), randomFrom(ByteSizeUnit.MB, ByteSizeUnit.GB))); } if (randomBoolean()) { builder.setDescription(randomAlphaOfLength(20)); } if (withGeneratedFields) { if (randomBoolean()) { builder.setCreateTime(Instant.now()); } if (randomBoolean()) { builder.setVersion(MlConfigVersion.CURRENT); } } if (randomBoolean()) { builder.setAllowLazyStart(randomBoolean()); } if (randomBoolean()) { builder.setMaxNumThreads(randomIntBetween(1, 20)); } if (randomBoolean()) { builder.setMeta(randomMeta()); } return builder; } public static String randomValidId() { CodepointSetGenerator generator = new CodepointSetGenerator("abcdefghijklmnopqrstuvwxyz".toCharArray()); return generator.ofCodePointsLength(random(), 10, 10); } // query:match:type stopped being supported in 6.x private static final String ANACHRONISTIC_QUERY_DATA_FRAME_ANALYTICS = """ { "id": "old-data-frame", "source": {"index":"my-index", "query": {"match" : {"query":"fieldName", "type": "phrase"}}}, "dest": {"index":"dest-index"}, "analysis": {"outlier_detection": {"n_neighbors": 10}} }"""; // match_all if parsed, adds default values in the options private static final String MODERN_QUERY_DATA_FRAME_ANALYTICS = """ { "id": "data-frame", "source": {"index":"my-index", "query": {"match_all" : {}}}, "dest": {"index":"dest-index"}, "analysis": {"outlier_detection": {"n_neighbors": 10}} }"""; private boolean lenient; @Before public void chooseStrictOrLenient() { lenient = randomBoolean(); } public void testQueryConfigStoresUserInputOnly() throws IOException { try (XContentParser parser = parser(MODERN_QUERY_DATA_FRAME_ANALYTICS)) { DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.LENIENT_PARSER.apply(parser, null).build(); assertThat(config.getSource().getQuery(), equalTo(Collections.singletonMap(MatchAllQueryBuilder.NAME, Collections.emptyMap()))); } try (XContentParser parser = parser(MODERN_QUERY_DATA_FRAME_ANALYTICS)) { DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.STRICT_PARSER.apply(parser, null).build(); assertThat(config.getSource().getQuery(), equalTo(Collections.singletonMap(MatchAllQueryBuilder.NAME, Collections.emptyMap()))); } } public void testPastQueryConfigParse() throws IOException { try (XContentParser parser = parser(ANACHRONISTIC_QUERY_DATA_FRAME_ANALYTICS)) { DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.LENIENT_PARSER.apply(parser, null).build(); ElasticsearchException e = expectThrows(ElasticsearchException.class, () -> config.getSource().getParsedQuery()); assertEquals("[match] query doesn't support multiple fields, found [query] and [type]", e.getMessage()); } try (XContentParser parser = parser(ANACHRONISTIC_QUERY_DATA_FRAME_ANALYTICS)) { XContentParseException e = expectThrows( XContentParseException.class, () -> DataFrameAnalyticsConfig.STRICT_PARSER.apply(parser, null).build() ); assertThat(e.getMessage(), containsString("[data_frame_analytics_config] failed to parse field [source]")); } } public void testToXContentForInternalStorage() throws IOException { DataFrameAnalyticsConfig.Builder builder = createRandomBuilder("foo"); // headers are only persisted to cluster state Map<String, String> headers = new HashMap<>(); headers.put("header-name", "header-value"); builder.setHeaders(headers); DataFrameAnalyticsConfig config = builder.build(); ToXContent.MapParams params = new ToXContent.MapParams(Collections.singletonMap(ToXContentParams.FOR_INTERNAL_STORAGE, "true")); BytesReference forClusterstateXContent = XContentHelper.toXContent(config, XContentType.JSON, params, false); XContentParser parser = parser(forClusterstateXContent); DataFrameAnalyticsConfig parsedConfig = DataFrameAnalyticsConfig.LENIENT_PARSER.apply(parser, null).build(); assertThat(parsedConfig.getHeaders(), hasEntry("header-name", "header-value")); // headers are not written without the FOR_INTERNAL_STORAGE param BytesReference nonClusterstateXContent = XContentHelper.toXContent(config, XContentType.JSON, ToXContent.EMPTY_PARAMS, false); parser = parser(nonClusterstateXContent); parsedConfig = DataFrameAnalyticsConfig.LENIENT_PARSER.apply(parser, null).build(); assertThat(parsedConfig.getHeaders().entrySet(), hasSize(0)); } public void testInvalidModelMemoryLimits() { DataFrameAnalyticsConfig.Builder builder = new DataFrameAnalyticsConfig.Builder(); // All these are different ways of specifying a limit that is lower than the minimum assertTooSmall( expectThrows( ElasticsearchStatusException.class, () -> builder.setModelMemoryLimit(ByteSizeValue.of(-1, ByteSizeUnit.BYTES)).build() ) ); assertTooSmall( expectThrows( ElasticsearchStatusException.class, () -> builder.setModelMemoryLimit(ByteSizeValue.of(0, ByteSizeUnit.BYTES)).build() ) ); assertTooSmall( expectThrows( ElasticsearchStatusException.class, () -> builder.setModelMemoryLimit(ByteSizeValue.of(0, ByteSizeUnit.KB)).build() ) ); assertTooSmall( expectThrows( ElasticsearchStatusException.class, () -> builder.setModelMemoryLimit(ByteSizeValue.of(0, ByteSizeUnit.MB)).build() ) ); assertTooSmall( expectThrows( ElasticsearchStatusException.class, () -> builder.setModelMemoryLimit(ByteSizeValue.of(1023, ByteSizeUnit.BYTES)).build() ) ); } public void testNoMemoryCapping() { DataFrameAnalyticsConfig uncapped = createRandom("foo"); ByteSizeValue unlimited = randomBoolean() ? null : ByteSizeValue.ZERO; assertThat( uncapped.getModelMemoryLimit(), equalTo(new DataFrameAnalyticsConfig.Builder(uncapped, unlimited).build().getModelMemoryLimit()) ); } public void testMemoryCapping() { DataFrameAnalyticsConfig defaultLimitConfig = createRandomBuilder("foo").setModelMemoryLimit(null).build(); ByteSizeValue maxLimit = ByteSizeValue.of(randomIntBetween(500, 1000), ByteSizeUnit.MB); if (maxLimit.compareTo(defaultLimitConfig.getModelMemoryLimit()) < 0) { assertThat(maxLimit, equalTo(new DataFrameAnalyticsConfig.Builder(defaultLimitConfig, maxLimit).build().getModelMemoryLimit())); } else { assertThat( defaultLimitConfig.getModelMemoryLimit(), equalTo(new DataFrameAnalyticsConfig.Builder(defaultLimitConfig, maxLimit).build().getModelMemoryLimit()) ); } } public void testExplicitModelMemoryLimitTooHigh() { ByteSizeValue configuredLimit = ByteSizeValue.of(randomIntBetween(5, 10), ByteSizeUnit.GB); DataFrameAnalyticsConfig explicitLimitConfig = createRandomBuilder("foo").setModelMemoryLimit(configuredLimit).build(); ByteSizeValue maxLimit = ByteSizeValue.of(randomIntBetween(500, 1000), ByteSizeUnit.MB); ElasticsearchStatusException e = expectThrows( ElasticsearchStatusException.class, () -> new DataFrameAnalyticsConfig.Builder(explicitLimitConfig, maxLimit).build() ); assertThat(e.getMessage(), startsWith("model_memory_limit")); assertThat(e.getMessage(), containsString("must be less than the value of the xpack.ml.max_model_memory_limit setting")); } public void testBuildForExplain() { DataFrameAnalyticsConfig.Builder builder = createRandomBuilder("foo"); DataFrameAnalyticsConfig config = builder.buildForExplain(); assertThat(config, equalTo(builder.build())); } public void testBuildForExplain_MissingId() { DataFrameAnalyticsConfig.Builder builder = new DataFrameAnalyticsConfig.Builder().setAnalysis(OutlierDetectionTests.createRandom()) .setSource(DataFrameAnalyticsSourceTests.createRandom()) .setDest(DataFrameAnalyticsDestTests.createRandom()); DataFrameAnalyticsConfig config = builder.buildForExplain(); assertThat(config.getId(), equalTo(DataFrameAnalyticsConfig.BLANK_ID)); } public void testBuildForExplain_MissingDest() { DataFrameAnalyticsConfig.Builder builder = new DataFrameAnalyticsConfig.Builder().setId("foo") .setAnalysis(OutlierDetectionTests.createRandom()) .setSource(DataFrameAnalyticsSourceTests.createRandom()); DataFrameAnalyticsConfig config = builder.buildForExplain(); assertThat(config.getDest().getIndex(), equalTo(DataFrameAnalyticsConfig.BLANK_DEST_INDEX)); } public void testPreventCreateTimeInjection() throws IOException { String json = """ { "create_time" : 123456789 }, "source" : {"index":"src"}, "dest" : {"index": "dest"},}"""; try (XContentParser parser = parser(json)) { Exception e = expectThrows(IllegalArgumentException.class, () -> DataFrameAnalyticsConfig.STRICT_PARSER.apply(parser, null)); assertThat(e.getMessage(), containsString("unknown field [create_time]")); } } public void testPreventVersionInjection() throws IOException { String json = """ { "version" : "7.3.0", "source" : {"index":"src"}, "dest" : {"index": "dest"},}"""; try (XContentParser parser = parser(json)) { Exception e = expectThrows(IllegalArgumentException.class, () -> DataFrameAnalyticsConfig.STRICT_PARSER.apply(parser, null)); assertThat(e.getMessage(), containsString("unknown field [version]")); } } public void testToXContent_GivenAnalysisWithRandomizeSeedAndVersionIsCurrent() throws IOException { Regression regression = new Regression("foo"); assertThat(regression.getRandomizeSeed(), is(notNullValue())); DataFrameAnalyticsConfig config = new DataFrameAnalyticsConfig.Builder().setVersion(MlConfigVersion.CURRENT) .setId("test_config") .setSource(new DataFrameAnalyticsSource(new String[] { "source_index" }, null, null, null)) .setDest(new DataFrameAnalyticsDest("dest_index", null)) .setAnalysis(regression) .build(); try (XContentBuilder builder = JsonXContent.contentBuilder()) { config.toXContent(builder, ToXContent.EMPTY_PARAMS); String json = Strings.toString(builder); assertThat(json, containsString("randomize_seed")); } } public void testExtractJobIdFromDocId() { assertThat(DataFrameAnalyticsConfig.extractJobIdFromDocId("data_frame_analytics_config-foo"), equalTo("foo")); assertThat( DataFrameAnalyticsConfig.extractJobIdFromDocId("data_frame_analytics_config-data_frame_analytics_config-foo"), equalTo("data_frame_analytics_config-foo") ); assertThat(DataFrameAnalyticsConfig.extractJobIdFromDocId("foo"), is(nullValue())); } public void testCtor_GivenMaxNumThreadsIsZero() { ElasticsearchException e = expectThrows( ElasticsearchException.class, () -> new DataFrameAnalyticsConfig.Builder().setId("test_config") .setSource(new DataFrameAnalyticsSource(new String[] { "source_index" }, null, null, null)) .setDest(new DataFrameAnalyticsDest("dest_index", null)) .setAnalysis(new Regression("foo")) .setMaxNumThreads(0) .build() ); assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST)); assertThat(e.getMessage(), equalTo("[max_num_threads] must be a positive integer")); } public void testCtor_GivenMaxNumThreadsIsNegative() { ElasticsearchException e = expectThrows( ElasticsearchException.class, () -> new DataFrameAnalyticsConfig.Builder().setId("test_config") .setSource(new DataFrameAnalyticsSource(new String[] { "source_index" }, null, null, null)) .setDest(new DataFrameAnalyticsDest("dest_index", null)) .setAnalysis(new Regression("foo")) .setMaxNumThreads(randomIntBetween(Integer.MIN_VALUE, 0)) .build() ); assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST)); assertThat(e.getMessage(), equalTo("[max_num_threads] must be a positive integer")); } private static void assertTooSmall(ElasticsearchStatusException e) { assertThat(e.getMessage(), startsWith("model_memory_limit must be at least 1kb.")); } private XContentParser parser(String json) throws IOException { return JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY.withRegistry(xContentRegistry()), json); } private XContentParser parser(BytesReference json) throws IOException { return JsonXContent.jsonXContent.createParser( XContentParserConfiguration.EMPTY.withRegistry(xContentRegistry()), json.streamInput() ); } public static Map<String, Object> randomMeta() { return rarely() ? null : randomMap(0, 10, () -> { String key = randomAlphaOfLengthBetween(1, 10); Object value = switch (randomIntBetween(0, 3)) { case 0 -> null; case 1 -> randomLong(); case 2 -> randomAlphaOfLengthBetween(1, 10); case 3 -> randomMap(0, 3, () -> Tuple.tuple(randomAlphaOfLengthBetween(1, 10), randomAlphaOfLengthBetween(1, 10))); default -> throw new AssertionError("Error in test code"); }; return Tuple.tuple(key, value); }); } }
DataFrameAnalyticsConfigTests
java
apache__spark
common/unsafe/src/main/java/org/apache/spark/sql/catalyst/util/CollationFactory.java
{ "start": 46093, "end": 59349 }
class ____ { private static int getSpecValue(int collationId, int offset, int mask) { return (collationId >> offset) & mask; } private static int removeSpec(int collationId, int offset, int mask) { return collationId & ~(mask << offset); } private static int setSpecValue(int collationId, int offset, Enum spec) { return collationId | (spec.ordinal() << offset); } } /** Returns the collation identifier. */ public CollationIdentifier identifier() { return new CollationIdentifier(provider, collationName, version); } } public static final String CATALOG = "SYSTEM"; public static final String SCHEMA = "BUILTIN"; public static final String PROVIDER_SPARK = "spark"; public static final String PROVIDER_ICU = "icu"; public static final String PROVIDER_NULL = "null"; public static final List<String> SUPPORTED_PROVIDERS = List.of(PROVIDER_SPARK, PROVIDER_ICU); public static final String PAD_ATTRIBUTE_EMPTY = "NO_PAD"; public static final String PAD_ATTRIBUTE_RTRIM = "RTRIM"; public static final int UTF8_BINARY_COLLATION_ID = Collation.CollationSpecUTF8.UTF8_BINARY_COLLATION_ID; public static final int UTF8_LCASE_COLLATION_ID = Collation.CollationSpecUTF8.UTF8_LCASE_COLLATION_ID; public static final int UNICODE_COLLATION_ID = Collation.CollationSpecICU.UNICODE_COLLATION_ID; public static final int UNICODE_CI_COLLATION_ID = Collation.CollationSpecICU.UNICODE_CI_COLLATION_ID; public static final int INDETERMINATE_COLLATION_ID = Collation.CollationSpec.INDETERMINATE_COLLATION_ID; /** * Returns a StringSearch object for the given pattern and target strings, under collation * rules corresponding to the given collationId. The external ICU library StringSearch object can * be used to find occurrences of the pattern in the target string, while respecting collation. * When given invalid UTF8Strings, the method will first convert them to valid strings, and then * instantiate the StringSearch object. However, original UTF8Strings will remain unchanged. */ public static StringSearch getStringSearch( final UTF8String targetUTF8String, final UTF8String patternUTF8String, final int collationId) { return getStringSearch(targetUTF8String.toValidString(), patternUTF8String.toValidString(), collationId); } /** * Returns a StringSearch object for the given pattern and target strings, under collation * rules corresponding to the given collationId. The external ICU library StringSearch object can * be used to find occurrences of the pattern in the target string, while respecting collation. */ public static StringSearch getStringSearch( final String targetString, final String patternString, final int collationId) { CharacterIterator target = new StringCharacterIterator(targetString); Collator collator = CollationFactory.fetchCollation(collationId).getCollator(); return new StringSearch(patternString, target, (RuleBasedCollator) collator); } /** * Returns a collation-unaware StringSearch object for the given pattern and target strings. * While this object does not respect collation, it can be used to find occurrences of the pattern * in the target string for UTF8_BINARY or UTF8_LCASE (if arguments are lowercased). * When given invalid UTF8Strings, the method will first convert them to valid strings, and then * instantiate the StringSearch object. However, original UTF8Strings will remain unchanged. */ public static StringSearch getStringSearch( final UTF8String targetUTF8String, final UTF8String patternUTF8String) { return new StringSearch(patternUTF8String.toValidString(), targetUTF8String.toValidString()); } /** * Returns the collation ID for the given collation name. */ public static int collationNameToId(String collationName) throws SparkException { return Collation.CollationSpec.collationNameToId(collationName); } /** * Returns the resolved fully qualified collation name. */ public static String resolveFullyQualifiedName(String[] collationName) throws SparkException { // If collation name has only one part, then we don't need to do any name resolution. if (collationName.length == 1) return collationName[0]; else { // Currently we only support builtin collation names with fixed catalog `SYSTEM` and // schema `BUILTIN`. if (collationName.length != 3 || !CollationFactory.CATALOG.equalsIgnoreCase(collationName[0]) || !CollationFactory.SCHEMA.equalsIgnoreCase(collationName[1])) { // Throw exception with original (before case conversion) collation name. throw CollationFactory.collationInvalidNameException( collationName.length != 0 ? collationName[collationName.length - 1] : ""); } return collationName[2]; } } /** * Method for constructing errors thrown on providing invalid collation name. */ public static SparkException collationInvalidNameException(String collationName) { Map<String, String> params = new HashMap<>(); final int maxSuggestions = 3; params.put("collationName", collationName); params.put("proposals", getClosestSuggestionsOnInvalidName(collationName, maxSuggestions)); return new SparkException("COLLATION_INVALID_NAME", SparkException.constructMessageParams(params), null); } /** * Returns the fully qualified collation name for the given collation ID. */ public static String fullyQualifiedName(int collationId) { if (collationId == INDETERMINATE_COLLATION_ID) { return Collation.CollationSpec.INDETERMINATE_COLLATION.collationName; } Collation.CollationSpec.DefinitionOrigin definitionOrigin = Collation.CollationSpec.getDefinitionOrigin(collationId); // Currently only predefined collations are supported. assert definitionOrigin == Collation.CollationSpec.DefinitionOrigin.PREDEFINED; return String.format("%s.%s.%s", CATALOG, SCHEMA, Collation.CollationSpec.fetchCollation(collationId).collationName); } public static boolean isCaseInsensitive(int collationId) { if (Collation.CollationSpec.getImplementationProvider(collationId) != Collation.CollationSpec.ImplementationProvider.ICU) { return false; } return Collation.CollationSpecICU.fromCollationId(collationId).caseSensitivity == Collation.CollationSpecICU.CaseSensitivity.CI; } public static boolean isAccentInsensitive(int collationId) { if (Collation.CollationSpec.getImplementationProvider(collationId) != Collation.CollationSpec.ImplementationProvider.ICU) { return false; } return Collation.CollationSpecICU.fromCollationId(collationId).accentSensitivity == Collation.CollationSpecICU.AccentSensitivity.AI; } public static void assertValidProvider(String provider) throws SparkException { if (!SUPPORTED_PROVIDERS.contains(provider.toLowerCase())) { Map<String, String> params = Map.of( "provider", provider, "supportedProviders", String.join(", ", SUPPORTED_PROVIDERS) ); throw new SparkException( "COLLATION_INVALID_PROVIDER", SparkException.constructMessageParams(params), null); } } public static Collation fetchCollation(int collationId) { return Collation.CollationSpec.fetchCollation(collationId); } public static Collation fetchCollation(String collationName) throws SparkException { return fetchCollation(collationNameToId(collationName)); } public static String[] getICULocaleNames() { return Collation.CollationSpecICU.ICULocaleNames; } /** * Applies trimming policy depending up on trim collation type. */ public static UTF8String applyTrimmingPolicy(UTF8String input, int collationId) { return Collation.CollationSpec.applyTrimmingPolicy(input, collationId); } /** * Returns if leading/trailing spaces should be ignored in trim string expressions. This is needed * because space trimming collation directly changes behaviour of trim functions. */ public static boolean ignoresSpacesInTrimFunctions( int collationId, boolean isLTrim, boolean isRTrim) { return Collation.CollationSpec.ignoresSpacesInTrimFunctions(collationId, isLTrim, isRTrim); } public static UTF8String getCollationKey(UTF8String input, int collationId) { Collation collation = fetchCollation(collationId); if (collation.supportsSpaceTrimming) { input = Collation.CollationSpec.applyTrimmingPolicy(input, collationId); } if (collation.isUtf8BinaryType) { return input; } else if (collation.isUtf8LcaseType) { return CollationAwareUTF8String.lowerCaseCodePoints(input); } else { CollationKey collationKey = collation.getCollator().getCollationKey( input.toValidString()); return UTF8String.fromBytes(collationKey.toByteArray()); } } public static byte[] getCollationKeyBytes(UTF8String input, int collationId) { Collation collation = fetchCollation(collationId); if (collation.supportsSpaceTrimming) { input = Collation.CollationSpec.applyTrimmingPolicy(input, collationId); } if (collation.isUtf8BinaryType) { return input.getBytes(); } else if (collation.isUtf8LcaseType) { return CollationAwareUTF8String.lowerCaseCodePoints(input).getBytes(); } else { return collation.getCollator().getCollationKey( input.toValidString()).toByteArray(); } } /** * Returns same string if collation name is valid or the closest suggestion if it is invalid. */ public static String getClosestSuggestionsOnInvalidName( String collationName, int maxSuggestions) { String[] validRootNames; String[] validModifiers; if (collationName.startsWith("UTF8_")) { validRootNames = new String[]{ Collation.CollationSpecUTF8.UTF8_BINARY_COLLATION.collationName, Collation.CollationSpecUTF8.UTF8_LCASE_COLLATION.collationName }; validModifiers = new String[]{"_RTRIM"}; } else { validRootNames = getICULocaleNames(); validModifiers = new String[]{"_CI", "_AI", "_CS", "_AS", "_RTRIM"}; } // Split modifiers and locale name. boolean foundModifier = true; String localeName = collationName.toUpperCase(); List<String> modifiers = new ArrayList<>(); while (foundModifier) { foundModifier = false; for (String modifier : validModifiers) { if (localeName.endsWith(modifier)) { modifiers.add(modifier); localeName = localeName.substring(0, localeName.length() - modifier.length()); foundModifier = true; break; } } } // Suggest version with unique modifiers. Collections.reverse(modifiers); modifiers = modifiers.stream().distinct().toList(); // Remove conflicting settings. if (modifiers.contains("_CI") && modifiers.contains(("_CS"))) { modifiers = modifiers.stream().filter(m -> !m.equals("_CI")).toList(); } if (modifiers.contains("_AI") && modifiers.contains(("_AS"))) { modifiers = modifiers.stream().filter(m -> !m.equals("_AI")).toList(); } final String finalLocaleName = localeName; Comparator<String> distanceComparator = (c1, c2) -> { int distance1 = UTF8String.fromString(c1.toUpperCase()) .levenshteinDistance(UTF8String.fromString(finalLocaleName)); int distance2 = UTF8String.fromString(c2.toUpperCase()) .levenshteinDistance(UTF8String.fromString(finalLocaleName)); return Integer.compare(distance1, distance2); }; String[] rootNamesByDistance = Arrays.copyOf(validRootNames, validRootNames.length); Arrays.sort(rootNamesByDistance, distanceComparator); Function<String, Boolean> isCollationNameValid = name -> { try { collationNameToId(name); return true; } catch (SparkException e) { return false; } }; final int suggestionThreshold = 3; final ArrayList<String> suggestions = new ArrayList<>(maxSuggestions); for (int i = 0; i < maxSuggestions; i++) { // Add at least one suggestion. // Add others if distance from the original is lower than threshold. String suggestion = rootNamesByDistance[i] + String.join("", modifiers); assert(isCollationNameValid.apply(suggestion)); if (suggestions.isEmpty()) { suggestions.add(suggestion); } else { int distance = UTF8String.fromString(suggestion.toUpperCase()) .levenshteinDistance(UTF8String.fromString(collationName.toUpperCase())); if (distance < suggestionThreshold) { suggestions.add(suggestion); } else { break; } } } return String.join(", ", suggestions); } public static List<CollationIdentifier> listCollations() { return Collation.CollationSpec.listCollations(); } public static CollationMeta loadCollationMeta(CollationIdentifier collationIdentifier) { return Collation.CollationSpec.loadCollationMeta(collationIdentifier); } }
SpecifierUtils
java
netty__netty
transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketTestPermutation.java
{ "start": 1690, "end": 10712 }
class ____ extends SocketTestPermutation { static final EpollSocketTestPermutation INSTANCE = new EpollSocketTestPermutation(); static final EventLoopGroup EPOLL_GROUP = new MultiThreadIoEventLoopGroup( NUM_THREADS, new DefaultThreadFactory("testsuite-epoll", true), EpollIoHandler.newFactory()); @Override public List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> socket() { List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> list = combo(serverSocket(), clientSocketWithFastOpen()); list.remove(list.size() - 1); // Exclude NIO x NIO test return list; } public List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> socketWithoutFastOpen() { List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> list = combo(serverSocket(), clientSocket()); list.remove(list.size() - 1); // Exclude NIO x NIO test return list; } @Override public List<BootstrapFactory<ServerBootstrap>> serverSocket() { List<BootstrapFactory<ServerBootstrap>> toReturn = new ArrayList<BootstrapFactory<ServerBootstrap>>(); toReturn.add(new BootstrapFactory<ServerBootstrap>() { @Override public ServerBootstrap newInstance() { return new ServerBootstrap().group(EPOLL_GROUP) .channel(EpollServerSocketChannel.class); } }); if (Epoll.isTcpFastOpenServerSideAvailable()) { toReturn.add(new BootstrapFactory<ServerBootstrap>() { @Override public ServerBootstrap newInstance() { ServerBootstrap serverBootstrap = new ServerBootstrap().group(EPOLL_GROUP) .channel(EpollServerSocketChannel.class); serverBootstrap.option(ChannelOption.TCP_FASTOPEN, 5); return serverBootstrap; } }); } toReturn.add(new BootstrapFactory<ServerBootstrap>() { @Override public ServerBootstrap newInstance() { return new ServerBootstrap().group(NIO_GROUP) .channel(NioServerSocketChannel.class); } }); return toReturn; } @Override public List<BootstrapFactory<Bootstrap>> clientSocket() { List<BootstrapFactory<Bootstrap>> toReturn = new ArrayList<BootstrapFactory<Bootstrap>>(); toReturn.add(new BootstrapFactory<Bootstrap>() { @Override public Bootstrap newInstance() { return new Bootstrap().group(EPOLL_GROUP).channel(EpollSocketChannel.class); } }); toReturn.add(new BootstrapFactory<Bootstrap>() { @Override public Bootstrap newInstance() { return new Bootstrap().group(NIO_GROUP).channel(NioSocketChannel.class); } }); return toReturn; } @Override public List<BootstrapFactory<Bootstrap>> clientSocketWithFastOpen() { List<BootstrapFactory<Bootstrap>> factories = clientSocket(); if (Epoll.isTcpFastOpenClientSideAvailable()) { int insertIndex = factories.size() - 1; // Keep NIO fixture last. factories.add(insertIndex, new BootstrapFactory<Bootstrap>() { @Override public Bootstrap newInstance() { return new Bootstrap().group(EPOLL_GROUP).channel(EpollSocketChannel.class) .option(ChannelOption.TCP_FASTOPEN_CONNECT, true); } }); } return factories; } @Override public List<TestsuitePermutation.BootstrapComboFactory<Bootstrap, Bootstrap>> datagram( final SocketProtocolFamily family) { // Make the list of Bootstrap factories. List<BootstrapFactory<Bootstrap>> bfs = Arrays.asList( new BootstrapFactory<Bootstrap>() { @Override public Bootstrap newInstance() { return new Bootstrap().group(NIO_GROUP).channelFactory(new ChannelFactory<Channel>() { @Override public Channel newChannel() { return new NioDatagramChannel(family); } @Override public String toString() { return NioDatagramChannel.class.getSimpleName() + ".class"; } }); } }, new BootstrapFactory<Bootstrap>() { @Override public Bootstrap newInstance() { return new Bootstrap().group(EPOLL_GROUP).channelFactory(new ChannelFactory<Channel>() { @Override public Channel newChannel() { return new EpollDatagramChannel(family); } @Override public String toString() { return InternetProtocolFamily.class.getSimpleName() + ".class"; } }); } } ); return combo(bfs, bfs); } List<TestsuitePermutation.BootstrapComboFactory<Bootstrap, Bootstrap>> epollOnlyDatagram( final SocketProtocolFamily family) { return combo(Collections.singletonList(datagramBootstrapFactory(family)), Collections.singletonList(datagramBootstrapFactory(family))); } private static BootstrapFactory<Bootstrap> datagramBootstrapFactory(final SocketProtocolFamily family) { return new BootstrapFactory<Bootstrap>() { @Override public Bootstrap newInstance() { return new Bootstrap().group(EPOLL_GROUP).channelFactory(new ChannelFactory<Channel>() { @Override public Channel newChannel() { return new EpollDatagramChannel(family); } @Override public String toString() { return SocketProtocolFamily.class.getSimpleName() + ".class"; } }); } }; } public List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> domainSocket() { return combo(serverDomainSocket(), clientDomainSocket()); } public List<BootstrapFactory<ServerBootstrap>> serverDomainSocket() { return Collections.<BootstrapFactory<ServerBootstrap>>singletonList( new BootstrapFactory<ServerBootstrap>() { @Override public ServerBootstrap newInstance() { return new ServerBootstrap().group(EPOLL_GROUP) .channel(EpollServerDomainSocketChannel.class); } } ); } public List<BootstrapFactory<Bootstrap>> clientDomainSocket() { return Collections.<BootstrapFactory<Bootstrap>>singletonList( new BootstrapFactory<Bootstrap>() { @Override public Bootstrap newInstance() { return new Bootstrap().group(EPOLL_GROUP).channel(EpollDomainSocketChannel.class); } } ); } @Override public List<BootstrapFactory<Bootstrap>> datagramSocket() { return Collections.<BootstrapFactory<Bootstrap>>singletonList( new BootstrapFactory<Bootstrap>() { @Override public Bootstrap newInstance() { return new Bootstrap().group(EPOLL_GROUP).channel(EpollDatagramChannel.class); } } ); } public List<TestsuitePermutation.BootstrapComboFactory<Bootstrap, Bootstrap>> domainDatagram() { return combo(domainDatagramSocket(), domainDatagramSocket()); } public List<BootstrapFactory<Bootstrap>> domainDatagramSocket() { return Collections.<BootstrapFactory<Bootstrap>>singletonList( new BootstrapFactory<Bootstrap>() { @Override public Bootstrap newInstance() { return new Bootstrap().group(EPOLL_GROUP).channel(EpollDomainDatagramChannel.class); } } ); } public static DomainSocketAddress newDomainSocketAddress() { return UnixTestUtils.newDomainSocketAddress(); } }
EpollSocketTestPermutation
java
elastic__elasticsearch
x-pack/plugin/transform/src/internalClusterTest/java/org/elasticsearch/xpack/transform/persistence/TransformConfigManagerTests.java
{ "start": 3521, "end": 36347 }
class ____ extends TransformSingleNodeTestCase { private IndexBasedTransformConfigManager transformConfigManager; private ClusterService clusterService; @Before public void createComponents() { clusterService = mock(); when(clusterService.state()).thenReturn(ClusterState.EMPTY_STATE); transformConfigManager = new IndexBasedTransformConfigManager( clusterService, TestIndexNameExpressionResolver.newInstance(), client(), xContentRegistry() ); } public void testGetMissingTransform() throws InterruptedException { // the index does not exist yet assertAsync( listener -> transformConfigManager.getTransformConfiguration("not_there", listener), (TransformConfig) null, null, e -> { assertEquals(ResourceNotFoundException.class, e.getClass()); assertEquals(TransformMessages.getMessage(TransformMessages.REST_UNKNOWN_TRANSFORM, "not_there"), e.getMessage()); } ); // create one transform and test with an existing index assertAsync( listener -> transformConfigManager.putTransformConfiguration(TransformConfigTests.randomTransformConfig(), listener), true, null, null ); // same test, but different code path assertAsync( listener -> transformConfigManager.getTransformConfiguration("not_there", listener), (TransformConfig) null, null, e -> { assertEquals(ResourceNotFoundException.class, e.getClass()); assertEquals(TransformMessages.getMessage(TransformMessages.REST_UNKNOWN_TRANSFORM, "not_there"), e.getMessage()); } ); } public void testDeleteMissingTransform() throws InterruptedException { // the index does not exist yet assertAsync(listener -> transformConfigManager.deleteTransform("not_there", listener), (Boolean) null, null, e -> { assertEquals(ResourceNotFoundException.class, e.getClass()); assertEquals(TransformMessages.getMessage(TransformMessages.REST_UNKNOWN_TRANSFORM, "not_there"), e.getMessage()); }); // create one transform and test with an existing index assertAsync( listener -> transformConfigManager.putTransformConfiguration(TransformConfigTests.randomTransformConfig(), listener), true, null, null ); // same test, but different code path assertAsync(listener -> transformConfigManager.deleteTransform("not_there", listener), (Boolean) null, null, e -> { assertEquals(ResourceNotFoundException.class, e.getClass()); assertEquals(TransformMessages.getMessage(TransformMessages.REST_UNKNOWN_TRANSFORM, "not_there"), e.getMessage()); }); } public void testCreateReadDeleteTransform() throws InterruptedException { TransformConfig transformConfig = TransformConfigTests.randomTransformConfig(); // create transform assertAsync(listener -> transformConfigManager.putTransformConfiguration(transformConfig, listener), true, null, null); // read transform assertAsync( listener -> transformConfigManager.getTransformConfiguration(transformConfig.getId(), listener), transformConfig, null, null ); // try to create again assertAsync(listener -> transformConfigManager.putTransformConfiguration(transformConfig, listener), (Boolean) null, null, e -> { assertEquals(ResourceAlreadyExistsException.class, e.getClass()); assertEquals( TransformMessages.getMessage(TransformMessages.REST_PUT_TRANSFORM_EXISTS, transformConfig.getId()), e.getMessage() ); }); // delete transform assertAsync(listener -> transformConfigManager.deleteTransform(transformConfig.getId(), listener), true, null, null); // delete again assertAsync(listener -> transformConfigManager.deleteTransform(transformConfig.getId(), listener), (Boolean) null, null, e -> { assertEquals(ResourceNotFoundException.class, e.getClass()); assertEquals(TransformMessages.getMessage(TransformMessages.REST_UNKNOWN_TRANSFORM, transformConfig.getId()), e.getMessage()); }); // try to get deleted transform assertAsync( listener -> transformConfigManager.getTransformConfiguration(transformConfig.getId(), listener), (TransformConfig) null, null, e -> { assertEquals(ResourceNotFoundException.class, e.getClass()); assertEquals( TransformMessages.getMessage(TransformMessages.REST_UNKNOWN_TRANSFORM, transformConfig.getId()), e.getMessage() ); } ); } public void testCreateReadDeleteCheckPoint() throws InterruptedException { TransformCheckpoint checkpoint = TransformCheckpointTests.randomTransformCheckpoint(); // create assertAsync(listener -> transformConfigManager.putTransformCheckpoint(checkpoint, listener), true, null, null); // read assertAsync( listener -> transformConfigManager.getTransformCheckpoint(checkpoint.getTransformId(), checkpoint.getCheckpoint(), listener), checkpoint, null, null ); // delete assertAsync(listener -> transformConfigManager.deleteTransform(checkpoint.getTransformId(), listener), true, null, null); // delete again assertAsync(listener -> transformConfigManager.deleteTransform(checkpoint.getTransformId(), listener), (Boolean) null, null, e -> { assertEquals(ResourceNotFoundException.class, e.getClass()); assertEquals( TransformMessages.getMessage(TransformMessages.REST_UNKNOWN_TRANSFORM, checkpoint.getTransformId()), e.getMessage() ); }); // getting a non-existing checkpoint returns null assertAsync( listener -> transformConfigManager.getTransformCheckpoint(checkpoint.getTransformId(), checkpoint.getCheckpoint(), listener), TransformCheckpoint.EMPTY, null, null ); } public void testExpandIds() throws Exception { TransformConfig transformConfig1 = TransformConfigTests.randomTransformConfig("transform1_expand"); TransformConfig transformConfig2 = TransformConfigTests.randomTransformConfig("transform2_expand"); TransformConfig transformConfig3 = TransformConfigTests.randomTransformConfig("transform3_expand"); // create transform assertAsync(listener -> transformConfigManager.putTransformConfiguration(transformConfig1, listener), true, null, null); assertAsync(listener -> transformConfigManager.putTransformConfiguration(transformConfig2, listener), true, null, null); assertAsync(listener -> transformConfigManager.putTransformConfiguration(transformConfig3, listener), true, null, null); // expand 1 id assertAsync( listener -> transformConfigManager.expandTransformIds( transformConfig1.getId(), PageParams.defaultParams(), null, true, listener ), tuple(1L, tuple(singletonList("transform1_expand"), singletonList(transformConfig1))), null, null ); // expand 2 ids explicitly assertAsync( listener -> transformConfigManager.expandTransformIds( "transform1_expand,transform2_expand", PageParams.defaultParams(), null, true, listener ), tuple(2L, tuple(Arrays.asList("transform1_expand", "transform2_expand"), Arrays.asList(transformConfig1, transformConfig2))), null, null ); // expand 3 ids wildcard and explicit assertAsync( listener -> transformConfigManager.expandTransformIds( "transform1*,transform2_expand,transform3_expand", PageParams.defaultParams(), null, true, listener ), tuple( 3L, tuple( Arrays.asList("transform1_expand", "transform2_expand", "transform3_expand"), Arrays.asList(transformConfig1, transformConfig2, transformConfig3) ) ), null, null ); // expand 3 ids _all assertAsync( listener -> transformConfigManager.expandTransformIds("_all", PageParams.defaultParams(), null, true, listener), tuple( 3L, tuple( Arrays.asList("transform1_expand", "transform2_expand", "transform3_expand"), Arrays.asList(transformConfig1, transformConfig2, transformConfig3) ) ), null, null ); // expand 1 id _all with pagination assertAsync( listener -> transformConfigManager.expandTransformIds("_all", new PageParams(0, 1), null, true, listener), tuple(3L, tuple(singletonList("transform1_expand"), singletonList(transformConfig1))), null, null ); // expand 2 later ids _all with pagination assertAsync( listener -> transformConfigManager.expandTransformIds("_all", new PageParams(1, 2), null, true, listener), tuple(3L, tuple(Arrays.asList("transform2_expand", "transform3_expand"), Arrays.asList(transformConfig2, transformConfig3))), null, null ); // expand 1 id explicitly that does not exist assertAsync( listener -> transformConfigManager.expandTransformIds("unknown,unknown2", new PageParams(1, 2), null, true, listener), (Tuple<Long, Tuple<List<String>, List<TransformConfig>>>) null, null, e -> { assertThat(e, instanceOf(ResourceNotFoundException.class)); assertThat( e.getMessage(), equalTo(TransformMessages.getMessage(TransformMessages.REST_UNKNOWN_TRANSFORM, "unknown,unknown2")) ); } ); // expand 1 id implicitly that does not exist assertAsync( listener -> transformConfigManager.expandTransformIds("unknown*", new PageParams(1, 2), null, false, listener), (Tuple<Long, Tuple<List<String>, List<TransformConfig>>>) null, null, e -> { assertThat(e, instanceOf(ResourceNotFoundException.class)); assertThat(e.getMessage(), equalTo(TransformMessages.getMessage(TransformMessages.REST_UNKNOWN_TRANSFORM, "unknown*"))); } ); // add a duplicate in an old index String oldIndex = TransformInternalIndexConstants.INDEX_PATTERN + "001"; String docId = TransformConfig.documentId(transformConfig2.getId()); TransformConfig transformConfig = TransformConfigTests.randomTransformConfig(transformConfig2.getId()); indicesAdmin().create(new CreateIndexRequest(oldIndex).mapping(mappings()).origin(ClientHelper.TRANSFORM_ORIGIN)).actionGet(); try (XContentBuilder builder = XContentFactory.jsonBuilder()) { XContentBuilder source = transformConfig.toXContent(builder, new ToXContent.MapParams(TO_XCONTENT_PARAMS)); IndexRequest request = new IndexRequest(oldIndex).source(source) .id(docId) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); client().index(request).actionGet(); } // check that transformConfig2 gets returned, not the one from the old index or both assertAsync( listener -> transformConfigManager.expandTransformIds( "transform1_expand,transform2_expand", PageParams.defaultParams(), null, true, listener ), tuple(2L, tuple(Arrays.asList("transform1_expand", "transform2_expand"), Arrays.asList(transformConfig1, transformConfig2))), null, null ); } public void testGetAllTransformIdsAndGetAllOutdatedTransformIds() throws Exception { long numberOfTransformsToGenerate = 100L; Set<String> transformIds = new HashSet<>(); for (long i = 0; i < numberOfTransformsToGenerate; ++i) { String id = "transform_" + i; transformIds.add(id); TransformConfig transformConfig = TransformConfigTests.randomTransformConfig(id); assertAsync(listener -> transformConfigManager.putTransformConfiguration(transformConfig, listener), true, null, null); } assertAsync(listener -> transformConfigManager.getAllTransformIds(null, listener), transformIds, null, null); // test recursive retrieval assertAsync( listener -> transformConfigManager.expandAllTransformIds(false, 10, null, listener), tuple(Long.valueOf(numberOfTransformsToGenerate), transformIds), null, null ); assertAsync( listener -> transformConfigManager.getAllOutdatedTransformIds(null, listener), tuple(Long.valueOf(numberOfTransformsToGenerate), Collections.<String>emptySet()), null, null ); assertAsync( listener -> transformConfigManager.expandAllTransformIds(true, 10, null, listener), tuple(Long.valueOf(numberOfTransformsToGenerate), Collections.<String>emptySet()), null, null ); // add a duplicate in an old index String oldIndex = TransformInternalIndexConstants.INDEX_PATTERN + "001"; String transformId = "transform_42"; String docId = TransformConfig.documentId(transformId); TransformConfig transformConfig = TransformConfigTests.randomTransformConfig(transformId); indicesAdmin().create(new CreateIndexRequest(oldIndex).mapping(mappings()).origin(ClientHelper.TRANSFORM_ORIGIN)).actionGet(); try (XContentBuilder builder = XContentFactory.jsonBuilder()) { XContentBuilder source = transformConfig.toXContent(builder, new ToXContent.MapParams(TO_XCONTENT_PARAMS)); IndexRequest request = new IndexRequest(oldIndex).source(source) .id(docId) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); client().index(request).actionGet(); } assertAsync(listener -> transformConfigManager.getAllTransformIds(null, listener), transformIds, null, null); assertAsync( listener -> transformConfigManager.getAllOutdatedTransformIds(null, listener), tuple(Long.valueOf(numberOfTransformsToGenerate), Collections.<String>emptySet()), null, null ); // add another old one, but not with an existing id final String oldTransformId = "transform_oldindex"; docId = TransformConfig.documentId(oldTransformId); transformConfig = TransformConfigTests.randomTransformConfig(oldTransformId); try (XContentBuilder builder = XContentFactory.jsonBuilder()) { XContentBuilder source = transformConfig.toXContent(builder, new ToXContent.MapParams(TO_XCONTENT_PARAMS)); IndexRequest request = new IndexRequest(oldIndex).source(source) .id(docId) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); client().index(request).actionGet(); } // add a new checkpoint doc for the old transform to check id expansion ignores other documents, see gh#80073 assertAsync( listener -> transformConfigManager.putTransformCheckpoint( TransformCheckpointTests.randomTransformCheckpoint(oldTransformId), listener ), true, null, null ); transformIds.add(oldTransformId); assertAsync(listener -> transformConfigManager.getAllTransformIds(null, listener), transformIds, null, null); assertAsync( listener -> transformConfigManager.getAllOutdatedTransformIds(null, listener), tuple(Long.valueOf(numberOfTransformsToGenerate + 1), Collections.singleton(oldTransformId)), null, null ); assertAsync( listener -> transformConfigManager.expandAllTransformIds(true, 10, null, listener), tuple(Long.valueOf(numberOfTransformsToGenerate + 1), Collections.singleton(oldTransformId)), null, null ); } public void testStoredDoc() throws InterruptedException { String transformId = "transform_test_stored_doc_create_read_update"; TransformStoredDoc storedDocs = TransformStoredDocTests.randomTransformStoredDoc(transformId); SeqNoPrimaryTermAndIndex firstIndex = new SeqNoPrimaryTermAndIndex(0, 1, TransformInternalIndexConstants.LATEST_INDEX_NAME); assertAsync(listener -> transformConfigManager.putOrUpdateTransformStoredDoc(storedDocs, null, listener), firstIndex, null, null); assertAsync( listener -> transformConfigManager.getTransformStoredDoc(transformId, false, listener), tuple(storedDocs, firstIndex), null, null ); SeqNoPrimaryTermAndIndex secondIndex = new SeqNoPrimaryTermAndIndex(1, 1, TransformInternalIndexConstants.LATEST_INDEX_NAME); TransformStoredDoc updated = TransformStoredDocTests.randomTransformStoredDoc(transformId); assertAsync( listener -> transformConfigManager.putOrUpdateTransformStoredDoc(updated, firstIndex, listener), secondIndex, null, null ); assertAsync( listener -> transformConfigManager.getTransformStoredDoc(transformId, false, listener), tuple(updated, secondIndex), null, null ); assertAsync( listener -> transformConfigManager.putOrUpdateTransformStoredDoc(updated, firstIndex, listener), (SeqNoPrimaryTermAndIndex) null, r -> fail("did not fail with version conflict."), e -> { assertThat( e.getMessage(), equalTo("Failed to persist transform statistics for transform [transform_test_stored_doc_create_read_update]") ); assertThat( "Consumers utilize ExceptionsHelper to check if there was a Version Conflict", ExceptionsHelper.unwrapCause(e), instanceOf(VersionConflictEngineException.class) ); } ); } public void testGetStoredDocMultiple() throws InterruptedException { int numStats = randomIntBetween(10, 15); List<TransformStoredDoc> expectedDocs = new ArrayList<>(); for (int i = 0; i < numStats; i++) { SeqNoPrimaryTermAndIndex initialSeqNo = new SeqNoPrimaryTermAndIndex(i, 1, TransformInternalIndexConstants.LATEST_INDEX_NAME); TransformStoredDoc stat = TransformStoredDocTests.randomTransformStoredDoc(randomAlphaOfLength(6) + i); expectedDocs.add(stat); assertAsync(listener -> transformConfigManager.putOrUpdateTransformStoredDoc(stat, null, listener), initialSeqNo, null, null); } // remove one of the put docs so we don't retrieve all if (expectedDocs.size() > 1) { expectedDocs.remove(expectedDocs.size() - 1); } List<String> ids = expectedDocs.stream().map(TransformStoredDoc::getId).collect(Collectors.toList()); // returned docs will be ordered by id expectedDocs.sort(Comparator.comparing(TransformStoredDoc::getId)); assertAsync(listener -> transformConfigManager.getTransformStoredDocs(ids, null, listener), expectedDocs, null, null); } public void testDeleteOldTransformConfigurations() throws Exception { String oldIndex = TransformInternalIndexConstants.INDEX_PATTERN + "001"; String transformId = "transform_test_delete_old_configurations"; String docId = TransformConfig.documentId(transformId); TransformConfig transformConfig = TransformConfigTests.randomTransformConfig("transform_test_delete_old_configurations"); indicesAdmin().create(new CreateIndexRequest(oldIndex).mapping(mappings()).origin(ClientHelper.TRANSFORM_ORIGIN)).actionGet(); try (XContentBuilder builder = XContentFactory.jsonBuilder()) { XContentBuilder source = transformConfig.toXContent(builder, new ToXContent.MapParams(TO_XCONTENT_PARAMS)); IndexRequest request = new IndexRequest(oldIndex).source(source) .id(docId) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); client().index(request).actionGet(); } assertAsync(listener -> transformConfigManager.putTransformConfiguration(transformConfig, listener), true, null, null); assertThat(client().get(new GetRequest(oldIndex).id(docId)).actionGet().isExists(), is(true)); assertThat( client().get(new GetRequest(TransformInternalIndexConstants.LATEST_INDEX_NAME).id(docId)).actionGet().isExists(), is(true) ); assertAsync(listener -> transformConfigManager.deleteOldTransformConfigurations(transformId, listener), true, null, null); indicesAdmin().refresh(new RefreshRequest(TransformInternalIndexConstants.INDEX_NAME_PATTERN)).actionGet(); assertThat(client().get(new GetRequest(oldIndex).id(docId)).actionGet().isExists(), is(false)); assertThat( client().get(new GetRequest(TransformInternalIndexConstants.LATEST_INDEX_NAME).id(docId)).actionGet().isExists(), is(true) ); } public void testDeleteOldTransformStoredDocuments() throws Exception { String oldIndex = TransformInternalIndexConstants.INDEX_PATTERN + "001"; String transformId = "transform_test_delete_old_stored_documents"; String docId = TransformStoredDoc.documentId(transformId); TransformStoredDoc transformStoredDoc = TransformStoredDocTests.randomTransformStoredDoc(transformId); indicesAdmin().create(new CreateIndexRequest(oldIndex).mapping(mappings()).origin(ClientHelper.TRANSFORM_ORIGIN)).actionGet(); try (XContentBuilder builder = XContentFactory.jsonBuilder()) { XContentBuilder source = transformStoredDoc.toXContent(builder, new ToXContent.MapParams(TO_XCONTENT_PARAMS)); IndexRequest request = new IndexRequest(oldIndex).source(source).id(docId); client().index(request).actionGet(); } // Put when referencing the old index should create the doc in the new index, even if we have seqNo|primaryTerm info assertAsync( listener -> transformConfigManager.putOrUpdateTransformStoredDoc( transformStoredDoc, new SeqNoPrimaryTermAndIndex(3, 1, oldIndex), listener ), new SeqNoPrimaryTermAndIndex(0, 1, TransformInternalIndexConstants.LATEST_INDEX_NAME), null, null ); indicesAdmin().refresh(new RefreshRequest(TransformInternalIndexConstants.INDEX_NAME_PATTERN)).actionGet(); assertThat(client().get(new GetRequest(oldIndex).id(docId)).actionGet().isExists(), is(true)); assertThat( client().get(new GetRequest(TransformInternalIndexConstants.LATEST_INDEX_NAME).id(docId)).actionGet().isExists(), is(true) ); assertAsync(listener -> transformConfigManager.deleteOldTransformStoredDocuments(transformId, listener), 1L, null, null); indicesAdmin().refresh(new RefreshRequest(TransformInternalIndexConstants.INDEX_NAME_PATTERN)).actionGet(); assertThat(client().get(new GetRequest(oldIndex).id(docId)).actionGet().isExists(), is(false)); assertThat( client().get(new GetRequest(TransformInternalIndexConstants.LATEST_INDEX_NAME).id(docId)).actionGet().isExists(), is(true) ); } public void testDeleteOldCheckpoints() throws InterruptedException { String transformId = randomAlphaOfLengthBetween(1, 10); long timestamp = System.currentTimeMillis() - randomLongBetween(20000, 40000); // create some other docs to check they are not getting accidentally deleted TransformStoredDoc storedDocs = TransformStoredDocTests.randomTransformStoredDoc(transformId); SeqNoPrimaryTermAndIndex firstIndex = new SeqNoPrimaryTermAndIndex(0, 1, TransformInternalIndexConstants.LATEST_INDEX_NAME); assertAsync(listener -> transformConfigManager.putOrUpdateTransformStoredDoc(storedDocs, null, listener), firstIndex, null, null); TransformConfig transformConfig = TransformConfigTests.randomTransformConfig(transformId); assertAsync(listener -> transformConfigManager.putTransformConfiguration(transformConfig, listener), true, null, null); // create 100 checkpoints for (int i = 1; i <= 100; i++) { TransformCheckpoint checkpoint = new TransformCheckpoint( transformId, timestamp + i * 200, i, emptyMap(), timestamp - 100 + i * 200 ); assertAsync(listener -> transformConfigManager.putTransformCheckpoint(checkpoint, listener), true, null, null); } // read a random checkpoint int randomCheckpoint = randomIntBetween(1, 100); TransformCheckpoint checkpointExpected = new TransformCheckpoint( transformId, timestamp + randomCheckpoint * 200, randomCheckpoint, emptyMap(), timestamp - 100 + randomCheckpoint * 200 ); assertAsync( listener -> transformConfigManager.getTransformCheckpoint(transformId, randomCheckpoint, listener), checkpointExpected, null, null ); // test delete based on checkpoint number (time would allow more) assertAsync( listener -> transformConfigManager.deleteOldCheckpoints(transformId, 11L, timestamp + 1 + 20L * 200, listener), 10L, null, null ); // test delete based on time (checkpoint number would allow more) assertAsync( listener -> transformConfigManager.deleteOldCheckpoints(transformId, 30L, timestamp + 1 + 20L * 200, listener), 10L, null, null ); // zero delete assertAsync( listener -> transformConfigManager.deleteOldCheckpoints(transformId, 30L, timestamp + 1 + 20L * 200, listener), 0L, null, null ); // delete the rest assertAsync( listener -> transformConfigManager.deleteOldCheckpoints(transformId, 101L, timestamp + 1 + 100L * 200, listener), 80L, null, null ); // test that the other docs are still there assertAsync( listener -> transformConfigManager.getTransformStoredDoc(transformId, false, listener), tuple(storedDocs, firstIndex), null, null ); assertAsync( listener -> transformConfigManager.getTransformConfiguration(transformConfig.getId(), listener), transformConfig, null, null ); } public void testDeleteOldIndices() throws Exception { String oldIndex = (randomBoolean() ? TransformInternalIndexConstants.INDEX_PATTERN : TransformInternalIndexConstants.INDEX_PATTERN_DEPRECATED) + "001"; String transformId = "transform_test_delete_old_indices"; String docId = TransformConfig.documentId(transformId); TransformConfig transformConfigOld = TransformConfigTests.randomTransformConfig(transformId); TransformConfig transformConfigNew = TransformConfigTests.randomTransformConfig(transformId); // create config in old index indicesAdmin().create(new CreateIndexRequest(oldIndex).mapping(mappings()).origin(ClientHelper.TRANSFORM_ORIGIN)).actionGet(); try (XContentBuilder builder = XContentFactory.jsonBuilder()) { XContentBuilder source = transformConfigOld.toXContent(builder, new ToXContent.MapParams(TO_XCONTENT_PARAMS)); IndexRequest request = new IndexRequest(oldIndex).source(source) .id(docId) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); client().index(request).actionGet(); } // create config in new index assertAsync(listener -> transformConfigManager.putTransformConfiguration(transformConfigNew, listener), true, null, null); assertThat(client().get(new GetRequest(oldIndex).id(docId)).actionGet().isExists(), is(true)); assertThat( client().get(new GetRequest(TransformInternalIndexConstants.LATEST_INDEX_NAME).id(docId)).actionGet().isExists(), is(true) ); // the new/latest one should be returned assertAsync(listener -> transformConfigManager.getTransformConfiguration(transformId, listener), transformConfigNew, null, null); // delete old indices when(clusterService.state()).thenReturn( createClusterStateWithTransformIndex(oldIndex, TransformInternalIndexConstants.LATEST_INDEX_NAME) ); assertAsync(listener -> transformConfigManager.deleteOldIndices(listener), true, null, null); // the config should still be there assertAsync(listener -> transformConfigManager.getTransformConfiguration(transformId, listener), transformConfigNew, null, null); // the old index should not exist anymore expectThrows( IndexNotFoundException.class, () -> assertThat(client().get(new GetRequest(oldIndex).id(docId)).actionGet().isExists(), is(false)) ); // but the latest one should assertThat( client().get(new GetRequest(TransformInternalIndexConstants.LATEST_INDEX_NAME).id(docId)).actionGet().isExists(), is(true) ); } private static ClusterState createClusterStateWithTransformIndex(String... indexes) throws IOException { Map<String, IndexMetadata> indexMapBuilder = new HashMap<>(); Metadata.Builder metaBuilder = Metadata.builder(); ClusterState.Builder csBuilder = ClusterState.builder(ClusterName.DEFAULT); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); for (String index : indexes) { IndexMetadata.Builder builder = new IndexMetadata.Builder(index).settings( Settings.builder() .put(TransformInternalIndex.settings(Settings.EMPTY)) .put(IndexMetadata.SETTING_INDEX_VERSION_CREATED.getKey(), IndexVersion.current()) .build() ).numberOfReplicas(0).numberOfShards(1).putMapping(Strings.toString(TransformInternalIndex.mappings())); final var indexMetadata = builder.build(); indexMapBuilder.put(index, indexMetadata); routingTableBuilder.add( IndexRoutingTable.builder(indexMetadata.getIndex()) .addShard( TestShardRouting.newShardRouting( new ShardId(indexMetadata.getIndex(), 0), "node_a", null, true, ShardRoutingState.STARTED ) ) .build() ); } csBuilder.routingTable(routingTableBuilder.build()); metaBuilder.indices(indexMapBuilder); csBuilder.metadata(metaBuilder.build()); return csBuilder.build(); } }
TransformConfigManagerTests
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java
{ "start": 4798, "end": 5179 }
class ____ the function's logic. * @param arguments Table and scalar argument {@link Expressions}. * @return The {@link Table} object describing the pipeline for further transformations. * @see Expressions#call(String, Object...) * @see ProcessTableFunction */ Table process(Class<? extends UserDefinedFunction> function, Object... arguments); }
containing
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolverTests.java
{ "start": 7611, "end": 8050 }
class ____ { public void handle() {} @ExceptionHandler({BindException.class, IllegalArgumentException.class}) public String handle1(Exception ex, HttpServletRequest request, HttpServletResponse response) { return ClassUtils.getShortName(ex.getClass()); } @ExceptionHandler public String handle2(IllegalArgumentException ex) { return ClassUtils.getShortName(ex.getClass()); } } @Controller static
AmbiguousController
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/file/ZstandardLoader.java
{ "start": 1420, "end": 2261 }
class ____ { static InputStream input(InputStream compressed, boolean useBufferPool) throws IOException { BufferPool pool = useBufferPool ? RecyclingBufferPool.INSTANCE : NoPool.INSTANCE; return new ZstdInputStreamNoFinalizer(compressed, pool); } static OutputStream output(OutputStream compressed, int level, boolean checksum, boolean useBufferPool) throws IOException { int bounded = Math.max(Math.min(level, Zstd.maxCompressionLevel()), Zstd.minCompressionLevel()); BufferPool pool = useBufferPool ? RecyclingBufferPool.INSTANCE : NoPool.INSTANCE; ZstdOutputStreamNoFinalizer zstdOutputStream = new ZstdOutputStreamNoFinalizer(compressed, pool).setLevel(bounded); zstdOutputStream.setCloseFrameOnFlush(false); zstdOutputStream.setChecksum(checksum); return zstdOutputStream; } }
ZstandardLoader
java
apache__flink
flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/testutils/HttpTestClient.java
{ "start": 3894, "end": 10047 }
class ____ implements AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(HttpTestClient.class); /** Target host to connect to. */ private final String host; /** Target port to connect to. */ private final int port; /** Netty's thread group for the client. */ private final EventLoopGroup group; /** Client bootstrap. */ private final Bootstrap bootstrap; /** Responses received by the client. */ private final BlockingQueue<SimpleHttpResponse> responses = new LinkedBlockingQueue<>(); /** * Creates a client instance for the server at the target host and port. * * @param host Host of the HTTP server * @param port Port of the HTTP server */ public HttpTestClient(String host, int port) { this.host = host; this.port = port; this.group = new NioEventLoopGroup(); this.bootstrap = new Bootstrap(); this.bootstrap .group(group) .channel(NioSocketChannel.class) .handler( new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec()); p.addLast(new HttpContentDecompressor()); p.addLast(new ClientHandler(responses)); } }); } /** * Sends a request to the server. * * <pre> * HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/overview"); * request.headers().set(HttpHeaderNames.HOST, host); * request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); * * sendRequest(request); * </pre> * * @param request The {@link HttpRequest} to send to the server */ public void sendRequest(HttpRequest request, Duration timeout) throws InterruptedException, TimeoutException { LOG.debug("Writing {}.", request); // Make the connection attempt. ChannelFuture connect = bootstrap.connect(host, port); Channel channel; if (connect.await(timeout.toMillis(), TimeUnit.MILLISECONDS)) { channel = connect.channel(); } else { throw new TimeoutException("Connection failed"); } channel.writeAndFlush(request); } /** * Sends a simple GET request to the given path. You only specify the $path part of * http://$host:$host/$path. * * @param path The $path to GET (http://$host:$host/$path) */ public void sendGetRequest(String path, Duration timeout) throws TimeoutException, InterruptedException { if (!path.startsWith("/")) { path = "/" + path; } HttpRequest getRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); getRequest.headers().set(HttpHeaderNames.HOST, host); getRequest.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); sendRequest(getRequest, timeout); } /** * Sends a simple DELETE request to the given path. You only specify the $path part of * http://$host:$host/$path. * * @param path The $path to DELETE (http://$host:$host/$path) */ public void sendDeleteRequest(String path, Duration timeout) throws TimeoutException, InterruptedException { if (!path.startsWith("/")) { path = "/" + path; } HttpRequest getRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, path); getRequest.headers().set(HttpHeaderNames.HOST, host); getRequest.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); sendRequest(getRequest, timeout); } /** * Sends a simple PATCH request to the given path. You only specify the $path part of * http://$host:$host/$path. * * @param path The $path to PATCH (http://$host:$host/$path) */ public void sendPatchRequest(String path, Duration timeout) throws TimeoutException, InterruptedException { if (!path.startsWith("/")) { path = "/" + path; } HttpRequest getRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PATCH, path); getRequest.headers().set(HttpHeaderNames.HOST, host); getRequest.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); sendRequest(getRequest, timeout); } /** * Returns the next available HTTP response. A call to this method blocks until a response * becomes available. * * @return The next available {@link SimpleHttpResponse} */ public SimpleHttpResponse getNextResponse() throws InterruptedException { return responses.take(); } /** * Returns the next available HTTP response . A call to this method blocks until a response * becomes available or throws an Exception if the timeout fires. * * @param timeout Timeout in milliseconds for the next response to become available * @return The next available {@link SimpleHttpResponse} */ public SimpleHttpResponse getNextResponse(Duration timeout) throws InterruptedException, TimeoutException { SimpleHttpResponse response = responses.poll(timeout.toMillis(), TimeUnit.MILLISECONDS); if (response == null) { throw new TimeoutException("No response within timeout of " + timeout + " ms"); } else { return response; } } /** Closes the client. */ @Override public void close() throws InterruptedException { if (group != null) { group.shutdownGracefully(); } LOG.debug("Closed"); } /** A simple HTTP response. */ public static
HttpTestClient
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/AbstractSimpleJsonTest.java
{ "start": 20518, "end": 20679 }
class ____ @SecureField directly, but with secured field's field returned testSecuredFieldOnAbstractClass("abstract-cat", "abstract-dog"); //
without
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/Camel4857UriIssueTest.java
{ "start": 2485, "end": 3930 }
class ____ extends DefaultComponent { @Override protected Endpoint createEndpoint(final String uri, final String remaining, final Map<String, Object> parameters) { return new MyEndpoint(uri, remaining); } @Override public boolean useRawUri() { // we want the raw uri, so our component can understand the endpoint // configuration as it was typed return true; } } @Override @BeforeEach public void setUp() throws Exception { super.setUp(); context.addComponent("my", new MyComponent()); } @Test public void testExclamationInUri() { // %3F is not an ?, it's part of tube name. MyEndpoint endpoint = context.getEndpoint("my:host:11303/tube1+tube%2B+tube%3F", MyEndpoint.class); assertNotNull(endpoint, "endpoint"); assertEquals("my:host:11303/tube1+tube%2B+tube%3F", endpoint.getUri()); } @Test public void testPath() { // Here a tube name is "tube+" and written in URI as "tube%2B", but it // gets // normalized, so that an endpoint sees "tube1+tube+" MyEndpoint endpoint = context.getEndpoint("my:host:11303/tube1+tube%2B", MyEndpoint.class); assertEquals("host:11303/tube1+tube%2B", endpoint.remaining, "Path contains several tube names, every tube name may have + or ? characters"); } }
MyComponent
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/bzip2/BZip2Constants.java
{ "start": 1257, "end": 4660 }
interface ____ { int baseBlockSize = 100000; int MAX_ALPHA_SIZE = 258; int MAX_CODE_LEN = 23; int RUNA = 0; int RUNB = 1; int N_GROUPS = 6; int G_SIZE = 50; int N_ITERS = 4; int MAX_SELECTORS = (2 + (900000 / G_SIZE)); int NUM_OVERSHOOT_BYTES = 20; /** * End of a BZip2 block */ public static final int END_OF_BLOCK = -2; /** * End of BZip2 stream. */ public static final int END_OF_STREAM = -1; /** * This array really shouldn't be here. Again, for historical purposes it * is. * * <p> * FIXME: This array should be in a private or package private location, * since it could be modified by malicious code. * </p> */ final int[] rNums = { 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, 936, 638 }; }
BZip2Constants
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_28.java
{ "start": 970, "end": 3092 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "/* 0a7d0d8614637128401131809d4d9d/9// */" + "SELECT id, name " + "FROM `t_0248` AS `i_trash` " + "WHERE `gmt_create` < DATE_ADD(NOW(), INTERVAL (- 7) DAY) " + "LIMIT 0, 1000"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); // print(statementList); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(3, visitor.getColumns().size()); assertEquals(1, visitor.getConditions().size()); assertEquals(0, visitor.getOrderByColumns().size()); { String output = SQLUtils.toMySqlString(stmt); assertEquals("/* 0a7d0d8614637128401131809d4d9d/9// */\n" + "SELECT id, name\n" + "FROM `t_0248` `i_trash`\n" + "WHERE `gmt_create` < DATE_ADD(NOW(), INTERVAL -7 DAY)\n" + "LIMIT 0, 1000", // output); } { String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION); assertEquals("/* 0a7d0d8614637128401131809d4d9d/9// */\n" + "select id, name\n" + "from `t_0248` `i_trash`\n" + "where `gmt_create` < DATE_ADD(NOW(), interval -7 day)\n" + "limit 0, 1000", // output); } } }
MySqlSelectTest_28
java
apache__spark
connector/kafka-0-10/src/test/java/org/apache/spark/streaming/kafka010/JavaKafkaRDDSuite.java
{ "start": 1466, "end": 4074 }
class ____ implements Serializable { private transient JavaSparkContext sc = null; private transient KafkaTestUtils kafkaTestUtils = null; @BeforeEach public void setUp() { kafkaTestUtils = new KafkaTestUtils(); kafkaTestUtils.setup(); SparkConf sparkConf = new SparkConf() .setMaster("local[4]").setAppName(this.getClass().getSimpleName()); sc = new JavaSparkContext(sparkConf); } @AfterEach public void tearDown() { if (sc != null) { sc.stop(); sc = null; } if (kafkaTestUtils != null) { kafkaTestUtils.teardown(); kafkaTestUtils = null; } } @Test public void testKafkaRDD() throws InterruptedException { String topic1 = "topic1"; String topic2 = "topic2"; Random random = new Random(); createTopicAndSendData(topic1); createTopicAndSendData(topic2); Map<String, Object> kafkaParams = new HashMap<>(); kafkaParams.put("bootstrap.servers", kafkaTestUtils.brokerAddress()); kafkaParams.put("key.deserializer", StringDeserializer.class); kafkaParams.put("value.deserializer", StringDeserializer.class); kafkaParams.put("group.id", "java-test-consumer-" + random.nextInt() + "-" + System.currentTimeMillis()); OffsetRange[] offsetRanges = { OffsetRange.create(topic1, 0, 0, 1), OffsetRange.create(topic2, 0, 0, 1) }; Map<TopicPartition, String> leaders = new HashMap<>(); String[] hostAndPort = kafkaTestUtils.brokerAddress().split(":"); String broker = hostAndPort[0]; leaders.put(offsetRanges[0].topicPartition(), broker); leaders.put(offsetRanges[1].topicPartition(), broker); Function<ConsumerRecord<String, String>, String> handler = ConsumerRecord::value; JavaRDD<String> rdd1 = KafkaUtils.<String, String>createRDD( sc, kafkaParams, offsetRanges, LocationStrategies.PreferFixed(leaders) ).map(handler); JavaRDD<String> rdd2 = KafkaUtils.<String, String>createRDD( sc, kafkaParams, offsetRanges, LocationStrategies.PreferConsistent() ).map(handler); // just making sure the java user APIs work; the scala tests handle logic corner cases long count1 = rdd1.count(); long count2 = rdd2.count(); Assertions.assertTrue(count1 > 0); Assertions.assertEquals(count1, count2); } private String[] createTopicAndSendData(String topic) { String[] data = { topic + "-1", topic + "-2", topic + "-3"}; kafkaTestUtils.createTopic(topic); kafkaTestUtils.sendMessages(topic, data); return data; } }
JavaKafkaRDDSuite
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_isAfterOrEqualTo_Test.java
{ "start": 1256, "end": 3647 }
class ____ extends LocalTimeAssertBaseTest { @Test void should_pass_if_actual_is_after_localTime_parameter() { assertThat(AFTER).isAfterOrEqualTo(REFERENCE); } @Test void should_pass_if_actual_is_after_localTime_as_string_parameter() { assertThat(AFTER).isAfterOrEqualTo(REFERENCE.toString()); } @Test void should_pass_if_actual_is_equal_to_localTime_parameter() { assertThat(REFERENCE).isAfterOrEqualTo(REFERENCE); } @Test void should_pass_if_actual_is_equal_to_localTime_as_string_parameter() { assertThat(REFERENCE).isAfterOrEqualTo(REFERENCE.toString()); } @Test void should_fail_if_actual_is_before_localTime_parameter() { // WHEN ThrowingCallable code = () -> assertThat(BEFORE).isAfterOrEqualTo(REFERENCE); // THEN assertThatAssertionErrorIsThrownBy(code).withMessage(shouldBeAfterOrEqualTo(BEFORE, REFERENCE).create()); } @Test void should_fail_if_actual_is_before_localTime_as_string_parameter() { // WHEN ThrowingCallable code = () -> assertThat(BEFORE).isAfterOrEqualTo(REFERENCE.toString()); // THEN assertThatAssertionErrorIsThrownBy(code).withMessage(shouldBeAfterOrEqualTo(BEFORE, REFERENCE).create()); } @Test void should_fail_if_actual_is_null() { // GIVEN LocalTime actual = null; // WHEN ThrowingCallable code = () -> assertThat(actual).isAfterOrEqualTo(LocalTime.now()); // THEN assertThatAssertionErrorIsThrownBy(code).withMessage(actualIsNull()); } @Test void should_fail_if_localTime_parameter_is_null() { // GIVEN LocalTime otherLocalTime = null; // WHEN ThrowingCallable code = () -> assertThat(LocalTime.now()).isAfterOrEqualTo(otherLocalTime); // THEN assertThatIllegalArgumentException().isThrownBy(code) .withMessage("The LocalTime to compare actual with should not be null"); } @Test void should_fail_if_localTime_as_string_parameter_is_null() { // GIVEN String otherLocalTimeAsString = null; // WHEN ThrowingCallable code = () -> assertThat(LocalTime.now()).isAfterOrEqualTo(otherLocalTimeAsString); // THEN assertThatIllegalArgumentException().isThrownBy(code) .withMessage("The String representing the LocalTime to compare actual with should not be null"); } }
LocalTimeAssert_isAfterOrEqualTo_Test
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/operators/GenericDataSinkBase.java
{ "start": 5947, "end": 9996 }
class ____ the output format. * @see org.apache.flink.api.common.operators.Operator#getUserCodeWrapper() */ @Override public UserCodeWrapper<? extends OutputFormat<IN>> getUserCodeWrapper() { return this.formatWrapper; } // -------------------------------------------------------------------------------------------- /** * Accepts the visitor and applies it this instance. This method applies the visitor in a * depth-first traversal. The visitors pre-visit method is called and, if returning * <tt>true</tt>, the visitor is recursively applied on the single input. After the recursion * returned, the post-visit method is called. * * @param visitor The visitor. * @see org.apache.flink.util.Visitable#accept(org.apache.flink.util.Visitor) */ @Override public void accept(Visitor<Operator<?>> visitor) { boolean descend = visitor.preVisit(this); if (descend) { this.input.accept(visitor); visitor.postVisit(this); } } // -------------------------------------------------------------------------------------------- @SuppressWarnings("unchecked") protected void executeOnCollections( List<IN> inputData, RuntimeContext ctx, ExecutionConfig executionConfig) throws Exception { OutputFormat<IN> format = this.formatWrapper.getUserCodeObject(); TypeInformation<IN> inputType = getInput().getOperatorInfo().getOutputType(); if (this.localOrdering != null) { int[] sortColumns = this.localOrdering.getFieldPositions(); boolean[] sortOrderings = this.localOrdering.getFieldSortDirections(); final TypeComparator<IN> sortComparator; if (inputType instanceof CompositeType) { sortComparator = ((CompositeType<IN>) inputType) .createComparator(sortColumns, sortOrderings, 0, executionConfig); } else if (inputType instanceof AtomicType) { sortComparator = ((AtomicType<IN>) inputType) .createComparator(sortOrderings[0], executionConfig); } else { throw new UnsupportedOperationException( "Local output sorting does not support type " + inputType + " yet."); } Collections.sort( inputData, new Comparator<IN>() { @Override public int compare(IN o1, IN o2) { return sortComparator.compare(o1, o2); } }); } if (format instanceof InitializeOnMaster) { ((InitializeOnMaster) format).initializeGlobal(1); } format.configure(this.parameters); if (format instanceof RichOutputFormat) { ((RichOutputFormat<?>) format).setRuntimeContext(ctx); } format.open(FirstAttemptInitializationContext.of(0, 1)); for (IN element : inputData) { format.writeRecord(element); } format.close(); if (format instanceof FinalizeOnMaster) { ((FinalizeOnMaster) format) .finalizeGlobal( new FinalizeOnMaster.FinalizationContext() { @Override public int getParallelism() { return 1; } @Override public int getFinishedAttempt(int subtaskIndex) { return 0; } }); } } // -------------------------------------------------------------------------------------------- @Override public String toString() { return this.name; } }
describing
java
alibaba__nacos
common/src/main/java/com/alibaba/nacos/common/codec/Base64.java
{ "start": 18700, "end": 24778 }
class ____ // Also ensures that the same roundings are performed by the ctor and the code Base64 b64 = isChunked ? new Base64(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe); long len = b64.getEncodedLength(binaryData); if (len > maxResultSize) { throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + len + ") than the specified maximum size of " + maxResultSize); } return b64.encode(binaryData); } /** * Decodes Base64 data into octets. * * @param base64Data Byte array containing Base64 data * @return Array containing decoded data. */ public static byte[] decodeBase64(byte[] base64Data) { return new Base64().decode(base64Data); } /** * MIME chunk size per RFC 2045 section 6.8. * * <p> The {@value} character limit does not count the trailing CRLF, but counts all other characters, including * any equal signs. </p> * * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a> */ private static final int MIME_CHUNK_SIZE = 76; private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2; /** * Defines the default buffer size - currently {@value} - must be large enough for at least one encoded * block+separator. */ private static final int DEFAULT_BUFFER_SIZE = 8192; /** * Mask used to extract 8 bits, used in decoding bytes. */ private static final int MASK_8BITS = 0xff; /** * Byte used to pad output. */ private static final byte PAD_DEFAULT = '='; private static final byte PAD = PAD_DEFAULT; /** * Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */ private final int unencodedBlockSize; /** * Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */ private final int encodedBlockSize; /** * Chunksize for encoding. Not used when decoding. A value of zero or less implies no chunking of the encoded data. * Rounded down to nearest multiple of encodedBlockSize. */ private final int lineLength; /** * Size of chunk separator. Not used unless {@link #lineLength} > 0. */ private final int chunkSeparatorLength; /** * Buffer for streaming. */ private byte[] buffer; /** * Position where next character should be written in the buffer. */ private int pos; /** * Position where next character should be read from the buffer. */ private int readPos; /** * Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, and * must be thrown away. */ private boolean eof; /** * Variable tracks how many characters have been written to the current line. Only used when encoding. We use it to * make sure each encoded line never goes beyond lineLength (if lineLength > 0). */ private int currentLinePos; /** * Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This * variable helps track that. */ private int modulus; /** * Ensure that the buffer has room for <code>size</code> bytes. * * @param size minimum spare space required */ private void ensureBufferSize(int size) { if ((buffer == null) || (buffer.length < pos + size)) { if (buffer == null) { buffer = new byte[DEFAULT_BUFFER_SIZE]; pos = 0; readPos = 0; } else { byte[] b = new byte[buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR]; System.arraycopy(buffer, 0, b, 0, buffer.length); buffer = b; } } } /** * Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail * bytes. Returns how many bytes were actually extracted. * * @param b byte[] array to extract the buffered data into. * @param bPos position in byte[] array to start extraction at. * @param bAvail amount of bytes we're allowed to extract. We may extract fewer (if fewer are available). * @return The number of bytes successfully extracted into the provided byte[] array. */ private int readResults(byte[] b, int bPos, int bAvail) { if (buffer != null) { int len = Math.min(pos - readPos, bAvail); System.arraycopy(buffer, readPos, b, bPos, len); readPos += len; if (readPos >= pos) { buffer = null; } return len; } return eof ? -1 : 0; } /** * Resets this object to its initial newly constructed state. */ private void reset() { buffer = null; pos = 0; readPos = 0; currentLinePos = 0; modulus = 0; eof = false; } /** * Calculates the amount of space needed to encode the supplied array. * * @param pArray byte[] array which will later be encoded * @return amount of space needed to encoded the supplied array. Returns a long since a max-len array will require > * Integer.MAX_VALUE */ private long getEncodedLength(byte[] pArray) { // Calculate non-chunked size - rounded up to allow for padding // cast to long is needed to avoid possibility of overflow long len = ((pArray.length + unencodedBlockSize - 1) / unencodedBlockSize) * (long) encodedBlockSize; if (lineLength > 0) { /* Round up to nearest multiple */ len += ((len + lineLength - 1) / lineLength) * chunkSeparatorLength; } return len; } }
method
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/fielddata/IpScriptFieldData.java
{ "start": 1029, "end": 3032 }
class ____ implements IndexFieldData.Builder { private final String name; private final IpFieldScript.LeafFactory leafFactory; private final ToScriptFieldFactory<SortedBinaryDocValues> toScriptFieldFactory; public Builder( String name, IpFieldScript.LeafFactory leafFactory, ToScriptFieldFactory<SortedBinaryDocValues> toScriptFieldFactory ) { this.name = name; this.leafFactory = leafFactory; this.toScriptFieldFactory = toScriptFieldFactory; } @Override public IpScriptFieldData build(IndexFieldDataCache cache, CircuitBreakerService breakerService) { return new IpScriptFieldData(name, leafFactory, toScriptFieldFactory); } } private final IpFieldScript.LeafFactory leafFactory; private final ToScriptFieldFactory<SortedBinaryDocValues> toScriptFieldFactory; private IpScriptFieldData( String fieldName, IpFieldScript.LeafFactory leafFactory, ToScriptFieldFactory<SortedBinaryDocValues> toScriptFieldFactory ) { super(fieldName); this.leafFactory = leafFactory; this.toScriptFieldFactory = toScriptFieldFactory; } @Override public BinaryScriptLeafFieldData loadDirect(LeafReaderContext context) throws Exception { IpFieldScript script = leafFactory.newInstance(context); return new BinaryScriptLeafFieldData() { @Override public DocValuesScriptFieldFactory getScriptFieldFactory(String name) { return toScriptFieldFactory.getScriptFieldFactory(getBytesValues(), name); } @Override public SortedBinaryDocValues getBytesValues() { return new org.elasticsearch.index.fielddata.IpScriptDocValues(script); } }; } @Override public ValuesSourceType getValuesSourceType() { return CoreValuesSourceType.IP; } }
Builder
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/class_/ClassAssert_isNotFinal_Test.java
{ "start": 1070, "end": 1827 }
class ____ { @Test void should_fail_if_actual_is_null() { // GIVEN Class<?> actual = null; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).isNotFinal()); // THEN then(assertionError).hasMessage(shouldNotBeNull().create()); } @Test void should_fail_if_actual_is_final() { // GIVEN Class<?> actual = String.class; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).isNotFinal()); // THEN then(assertionError).hasMessage(shouldNotBeFinal(actual).create()); } @Test void should_pass_if_actual_is_not_final() { // GIVEN Class<?> actual = Object.class; // WHEN/THEN assertThat(actual).isNotFinal(); } }
ClassAssert_isNotFinal_Test
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/cli/util/TokenComparator.java
{ "start": 1067, "end": 1556 }
class ____ extends ComparatorBase { @Override public boolean compare(String actual, String expected) { boolean compareOutput = true; StringTokenizer tokenizer = new StringTokenizer(expected, ",\n\r"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (actual.indexOf(token) != -1) { compareOutput &= true; } else { compareOutput &= false; } } return compareOutput; } }
TokenComparator
java
apache__camel
components/camel-smb/src/test/java/org/apache/camel/component/smb/FromSmbToAsciiFileIT.java
{ "start": 1287, "end": 3278 }
class ____ extends SmbServerTestSupport { @TempDir Path testDirectory; protected String getSmbUrl() { return String.format( "smb:%s/%s/toasciifile?username=%s&password=%s&fileExist=Override", service.address(), service.shareName(), service.userName(), service.password()); } @Override public void doPostSetup() throws Exception { prepareSmbServer(); } @Test public void testSmbRoute() throws Exception { MockEndpoint resultEndpoint = getMockEndpoint("mock:result"); resultEndpoint.expectedMinimumMessageCount(1); resultEndpoint.expectedBodiesReceived("Hello World from SMBServer"); resultEndpoint.assertIsSatisfied(); // assert the file File file = testDirectory.resolve("deleteme.txt").toFile(); assertTrue(file.exists(), "The ASCII file should exists"); assertTrue(file.length() > 10, "File size wrong"); } private void prepareSmbServer() throws Exception { // prepares the SMB Server by creating a file on the server that we want // to unit test that we can pool and store as a local file Endpoint endpoint = context.getEndpoint(getSmbUrl()); Exchange exchange = endpoint.createExchange(); exchange.getIn().setBody("Hello World from SMBServer"); exchange.getIn().setHeader(Exchange.FILE_NAME, "hello.txt"); Producer producer = endpoint.createProducer(); producer.start(); producer.process(exchange); producer.stop(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(getSmbUrl()).setHeader(Exchange.FILE_NAME, constant("deleteme.txt")).convertBodyTo(String.class) .to(TestSupport.fileUri(testDirectory, "?fileExist=Override&noop=true")).to("mock:result"); } }; } }
FromSmbToAsciiFileIT
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/uri/UriAssert_hasHost_Test.java
{ "start": 871, "end": 1216 }
class ____ extends UriAssertBaseTest { private String expected = "host"; @Override protected UriAssert invoke_api_method() { return assertions.hasHost(expected); } @Override protected void verify_internal_effects() { verify(uris).assertHasHost(getInfo(assertions), getActual(assertions), expected); } }
UriAssert_hasHost_Test
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/support/component/ApiConsumerHelper.java
{ "start": 1150, "end": 3836 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(ApiConsumerHelper.class); private ApiConsumerHelper() { } /** * Utility method to find matching API Method for supplied endpoint's configuration properties. * * @param endpoint endpoint for configuration properties. * @param propertyNamesInterceptor names interceptor for adapting property names, usually the consumer class * itself. * @param <E> ApiName enumeration. * @param <T> Component configuration class. * @return matching ApiMethod. */ public static <E extends Enum<E> & ApiName, T> ApiMethod findMethod( AbstractApiEndpoint<E, T> endpoint, PropertyNamesInterceptor propertyNamesInterceptor) { ApiMethod result; // find one that takes the largest subset of endpoint parameters Set<String> names = endpoint.getEndpointPropertyNames(); final Set<String> argNames = new HashSet<>(names); propertyNamesInterceptor.interceptPropertyNames(argNames); List<ApiMethod> filteredMethods = endpoint.methodHelper.filterMethods( endpoint.getCandidates(), ApiMethodHelper.MatchType.SUPER_SET, argNames); if (filteredMethods.isEmpty()) { ApiMethodHelper<? extends ApiMethod> methodHelper = endpoint.getMethodHelper(); throw new IllegalArgumentException( String.format("Missing properties for %s/%s, need one or more from %s", endpoint.getApiName().getName(), endpoint.getMethodName(), methodHelper.getMissingProperties(endpoint.getMethodName(), argNames))); } else if (filteredMethods.size() == 1) { // single match result = filteredMethods.get(0); } else { result = ApiMethodHelper.getHighestPriorityMethod(filteredMethods); LOG.warn("Using highest priority operation {} from operations {} for endpoint {}", result, filteredMethods, endpoint.getEndpointUri()); } return result; } /** * Utility method for Consumers to process API method invocation result. * * @param consumer Consumer that wants to process results. * @param result result of API method invocation. * @param splitResult true if the Consumer wants to split result using * {@link org.apache.camel.support.component.ResultInterceptor#splitResult(Object)} method. * @param <T> Consumer
ApiConsumerHelper
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/concurrent/package-info.java
{ "start": 2372, "end": 3962 }
class ____ be used to defer the creation of an object * until it is actually used. This makes sense, for instance, if the creation of the object is expensive and would slow * down application startup or if the object is needed only for special executions. * {@link org.apache.commons.lang3.concurrent.LazyInitializer} implements the <em>double-check idiom for an instance * field</em> as discussed in Joshua Bloch's "Effective Java", 2nd edition, item 71. It uses <strong>volatile</strong> * fields to reduce the amount of synchronization. Note that this idiom is appropriate for instance fields only. For * <strong>static</strong> fields there are superior alternatives. * </p> * * <p> * We provide an example use case to demonstrate the usage of this class: A server application uses multiple worker * threads to process client requests. If such a request causes a fatal error, an administrator is to be notified using * a special messaging service. We assume that the creation of the messaging service is an expensive operation. So it * should only be performed if an error actually occurs. Here is where * {@link org.apache.commons.lang3.concurrent.LazyInitializer} comes into play. We create a specialized subclass for * creating and initializing an instance of our messaging service. * {@link org.apache.commons.lang3.concurrent.LazyInitializer} declares an abstract * {@link org.apache.commons.lang3.concurrent.LazyInitializer#initialize() initialize()} method which we have to * implement to create the messaging service object: * </p> * * <pre>{@code * public
can
java
apache__flink
flink-core/src/main/java/org/apache/flink/configuration/StateBackendOptions.java
{ "start": 2778, "end": 3600 }
class ____ of a %s. " + "If a factory is specified it is instantiated via its " + "zero argument constructor and its %s " + "method is called.", TextElement.code("StateBackendFactory"), TextElement.code( "StateBackendFactory#createFromConfig(ReadableConfig, ClassLoader)")) .linebreak() .text( "Recognized shortcut names are 'hashmap', 'rocksdb' and 'forst'.") .build()); }
name
java
quarkusio__quarkus
extensions/grpc/runtime/src/main/java/io/quarkus/grpc/runtime/supports/blocking/DevModeBlockingExecutionHandler.java
{ "start": 91, "end": 736 }
class ____ implements Callable<Void> { final ClassLoader tccl; final Callable<Void> delegate; public DevModeBlockingExecutionHandler(ClassLoader tccl, Callable<Void> delegate) { this.tccl = tccl; this.delegate = delegate; } @Override public Void call() throws Exception { ClassLoader originalTccl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(tccl); try { return delegate.call(); } finally { Thread.currentThread().setContextClassLoader(originalTccl); } } }
DevModeBlockingExecutionHandler
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/rules/logical/PushDownJoinPastProject.java
{ "start": 2194, "end": 7124 }
class ____ extends OptimizerRules.OptimizerRule<Join> { @Override protected LogicalPlan rule(Join join) { if (join instanceof InlineJoin) { // Do not apply to INLINE STATS; this rule could be expanded to include INLINE STATS, but the StubRelation refers to the left // child - so pulling out a Project from the left child would require us to also update the StubRelation (and the Aggregate // on top of it) // TODO: figure out how to push down in case of INLINE STATS return join; } if (join.left() instanceof Project project && join.config().type() == JoinTypes.LEFT) { AttributeMap.Builder<Expression> aliasBuilder = AttributeMap.builder(); project.forEachExpression(Alias.class, a -> aliasBuilder.put(a.toAttribute(), a.child())); var aliasesFromProject = aliasBuilder.build(); // Propagate any renames into the Join, as we will remove the upstream Project. // E.g. `RENAME field AS key | LOOKUP JOIN idx ON key` -> `LOOKUP JOIN idx ON field | ...` Join updatedJoin = PushDownUtils.resolveRenamesFromMap(join, aliasesFromProject); // Construct the expressions for the new downstream Project using the Join's output. // We need to carry over RENAMEs/aliases from the original upstream Project. List<Attribute> originalOutput = join.output(); List<NamedExpression> newProjections = new ArrayList<>(originalOutput.size()); for (Attribute attr : originalOutput) { Attribute resolved = (Attribute) aliasesFromProject.resolve(attr, attr); if (attr.semanticEquals(resolved)) { newProjections.add(attr); } else { Alias renamed = new Alias(attr.source(), attr.name(), resolved, attr.id(), attr.synthetic()); newProjections.add(renamed); } } // This doesn't deal with name conflicts yet. Any name shadowed by a lookup field from the `LOOKUP JOIN` could still have been // used in the original Project; any such conflict needs to be resolved by copying the attribute under a temporary name via an // Eval - and using the attribute from said Eval in the new downstream Project. Set<String> lookupFieldNames = new HashSet<>(Expressions.names(join.rightOutputFields())); List<NamedExpression> finalProjections = new ArrayList<>(newProjections.size()); AttributeMap.Builder<Alias> aliasesForReplacedAttributesBuilder = AttributeMap.builder(); AttributeSet leftOutput = project.child().outputSet(); for (NamedExpression newProj : newProjections) { Attribute coreAttr = (Attribute) Alias.unwrap(newProj); // Only fields from the left need to be protected from conflicts - because fields from the right shadow them. if (leftOutput.contains(coreAttr) && lookupFieldNames.contains(coreAttr.name())) { // Conflict - the core attribute will be shadowed by the `LOOKUP JOIN` and we need to alias it in an upstream Eval. Alias renaming = aliasesForReplacedAttributesBuilder.computeIfAbsent(coreAttr, a -> { String tempName = TemporaryNameUtils.locallyUniqueTemporaryName(a.name()); return new Alias(a.source(), tempName, a, null, true); }); Attribute renamedAttribute = renaming.toAttribute(); Alias renamedBack; if (newProj instanceof Alias as) { renamedBack = new Alias(as.source(), as.name(), renamedAttribute, as.id(), as.synthetic()); } else { // no alias - that means proj == coreAttr renamedBack = new Alias(coreAttr.source(), coreAttr.name(), renamedAttribute, coreAttr.id(), coreAttr.synthetic()); } finalProjections.add(renamedBack); } else { finalProjections.add(newProj); } } if (aliasesForReplacedAttributesBuilder.isEmpty()) { // No name conflicts, so no eval needed. return new Project(project.source(), updatedJoin.replaceLeft(project.child()), newProjections); } List<Alias> renamesForEval = new ArrayList<>(aliasesForReplacedAttributesBuilder.build().values()); Eval eval = new Eval(project.source(), project.child(), renamesForEval); Join finalJoin = new Join(join.source(), eval, updatedJoin.right(), updatedJoin.config()); return new Project(project.source(), finalJoin, finalProjections); } return join; } }
PushDownJoinPastProject
java
netty__netty
transport-native-io_uring/src/test/java/io/netty/channel/uring/IoUringBufferRingSocketEchoTest.java
{ "start": 1062, "end": 1824 }
class ____ extends SocketEchoTest { @BeforeAll public static void loadJNI() { assumeTrue(IoUring.isAvailable()); assumeTrue(IoUring.isRegisterBufferRingSupported()); } @Override protected List<BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() { return IoUringSocketTestPermutation.INSTANCE.socket(); } @Override protected void configure(ServerBootstrap sb, Bootstrap cb, ByteBufAllocator allocator) { super.configure(sb, cb, allocator); sb.childOption(IoUringChannelOption.IO_URING_BUFFER_GROUP_ID, IoUringSocketTestPermutation.BGID); cb.option(IoUringChannelOption.IO_URING_BUFFER_GROUP_ID, IoUringSocketTestPermutation.BGID); } }
IoUringBufferRingSocketEchoTest
java
google__error-prone
core/src/test/java/com/google/errorprone/matchers/MethodReturnsNonNullNextTokenTest.java
{ "start": 2210, "end": 3311 }
class ____ extends StringTokenizer { public A(String str, String delim, boolean returnDelims) { super(str, delim, returnDelims); } @Override public String nextToken() { return "overridden method"; } public void testOverriddenNextToken() { nextToken(); } } """); assertCompiles( methodInvocationMatches(/* shouldMatch= */ false, Matchers.methodReturnsNonNull())); } private Scanner methodInvocationMatches(boolean shouldMatch, Matcher<ExpressionTree> toMatch) { return new Scanner() { @Override public Void visitMethodInvocation(MethodInvocationTree node, VisitorState visitorState) { ExpressionTree methodSelect = node.getMethodSelect(); if (!methodSelect.toString().equals("super")) { assertWithMessage(methodSelect.toString()) .that(!shouldMatch ^ toMatch.matches(node, visitorState)) .isTrue(); } return super.visitMethodInvocation(node, visitorState); } }; } }
A
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/query/WrapperQueryBuilderTests.java
{ "start": 1425, "end": 9960 }
class ____ extends AbstractQueryTestCase<WrapperQueryBuilder> { @Override protected boolean supportsBoost() { return false; } @Override protected boolean supportsQueryName() { return false; } @Override protected boolean builderGeneratesCacheableQueries() { return false; } @Override protected WrapperQueryBuilder doCreateTestQueryBuilder() { QueryBuilder wrappedQuery = RandomQueryBuilder.createQuery(random()); BytesReference bytes; try { bytes = XContentHelper.toXContent(wrappedQuery, XContentType.JSON, false); } catch (IOException e) { throw new UncheckedIOException(e); } return switch (randomInt(2)) { case 0 -> new WrapperQueryBuilder(wrappedQuery.toString()); case 1 -> new WrapperQueryBuilder(BytesReference.toBytes(bytes)); case 2 -> new WrapperQueryBuilder(bytes); default -> throw new UnsupportedOperationException(); }; } @Override protected void doAssertLuceneQuery(WrapperQueryBuilder queryBuilder, Query query, SearchExecutionContext context) throws IOException { QueryBuilder innerQuery = queryBuilder.rewrite(createSearchExecutionContext()); Query expected = rewrite(innerQuery.toQuery(context)); assertEquals(rewrite(query), expected); } public void testIllegalArgument() { expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder((byte[]) null)); expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder(new byte[0])); expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder((String) null)); expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder("")); expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder((BytesReference) null)); expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder(new BytesArray(new byte[0]))); } /** * Replace the generic test from superclass, wrapper query only expects * to find `query` field with nested query and should throw exception for * anything else. */ @Override public void testUnknownField() { String json = "{ \"" + WrapperQueryBuilder.NAME + "\" : {\"bogusField\" : \"someValue\"} }"; ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json)); assertTrue(e.getMessage().contains("bogusField")); } public void testFromJson() throws IOException { String json = """ { "wrapper" : { "query" : "e30=" } }"""; WrapperQueryBuilder parsed = (WrapperQueryBuilder) parseQuery(json); checkGeneratedJson(json, parsed); assertEquals(json, "{}", new String(parsed.source(), StandardCharsets.UTF_8)); } @Override public void testMustRewrite() throws IOException { TermQueryBuilder tqb = new TermQueryBuilder(TEXT_FIELD_NAME, "bar"); WrapperQueryBuilder qb = new WrapperQueryBuilder(tqb.toString()); UnsupportedOperationException e = expectThrows( UnsupportedOperationException.class, () -> qb.toQuery(createSearchExecutionContext()) ); assertEquals("this query must be rewritten first", e.getMessage()); QueryBuilder rewrite = qb.rewrite(createSearchExecutionContext()); assertEquals(tqb, rewrite); } public void testRewriteWithInnerName() throws IOException { QueryBuilder builder = new WrapperQueryBuilder(""" { "match_all" : {"_name" : "foobar"}}"""); SearchExecutionContext searchExecutionContext = createSearchExecutionContext(); assertEquals(new MatchAllQueryBuilder().queryName("foobar"), builder.rewrite(searchExecutionContext)); builder = new WrapperQueryBuilder(""" { "match_all" : {"_name" : "foobar"}}""").queryName("outer"); assertEquals( new BoolQueryBuilder().must(new MatchAllQueryBuilder().queryName("foobar")).queryName("outer"), builder.rewrite(searchExecutionContext) ); } public void testRewriteWithInnerBoost() throws IOException { final TermQueryBuilder query = new TermQueryBuilder(TEXT_FIELD_NAME, "bar").boost(2); QueryBuilder builder = new WrapperQueryBuilder(query.toString()); SearchExecutionContext searchExecutionContext = createSearchExecutionContext(); assertEquals(query, builder.rewrite(searchExecutionContext)); builder = new WrapperQueryBuilder(query.toString()).boost(3); assertEquals(new BoolQueryBuilder().must(query).boost(3), builder.rewrite(searchExecutionContext)); } public void testRewriteInnerQueryToo() throws IOException { SearchExecutionContext searchExecutionContext = createSearchExecutionContext(); QueryBuilder qb = new WrapperQueryBuilder( new WrapperQueryBuilder(new TermQueryBuilder(TEXT_FIELD_NAME, "bar").toString()).toString() ); assertEquals(new TermQuery(new Term(TEXT_FIELD_NAME, "bar")), qb.rewrite(searchExecutionContext).toQuery(searchExecutionContext)); qb = new WrapperQueryBuilder( new WrapperQueryBuilder(new WrapperQueryBuilder(new TermQueryBuilder(TEXT_FIELD_NAME, "bar").toString()).toString()).toString() ); assertEquals(new TermQuery(new Term(TEXT_FIELD_NAME, "bar")), qb.rewrite(searchExecutionContext).toQuery(searchExecutionContext)); qb = new WrapperQueryBuilder(new BoolQueryBuilder().toString()); assertEquals(new MatchAllDocsQuery(), qb.rewrite(searchExecutionContext).toQuery(searchExecutionContext)); } @Override protected Query rewrite(Query query) throws IOException { // WrapperQueryBuilder adds some optimization if the wrapper and query builder have boosts / query names that wraps // the actual QueryBuilder that comes from the binary blob into a BooleanQueryBuilder to give it an outer boost / name // this causes some queries to be not exactly equal but equivalent such that we need to rewrite them before comparing. if (query != null) { MemoryIndex idx = new MemoryIndex(); return idx.createSearcher().rewrite(query); } return new MatchAllDocsQuery(); // null == *:* } @Override protected WrapperQueryBuilder createQueryWithInnerQuery(QueryBuilder queryBuilder) { return new WrapperQueryBuilder(Strings.toString(queryBuilder)); } public void testMaxNestedDepth() throws IOException { BoolQueryBuilderTests boolQueryBuilderTests = new BoolQueryBuilderTests(); BoolQueryBuilder boolQuery = boolQueryBuilderTests.createQueryWithInnerQuery(new MatchAllQueryBuilder()); int maxDepth = randomIntBetween(3, 5); AbstractQueryBuilder.setMaxNestedDepth(maxDepth); for (int i = 1; i < maxDepth - 1; i++) { boolQuery = boolQueryBuilderTests.createQueryWithInnerQuery(boolQuery); } WrapperQueryBuilder query = new WrapperQueryBuilder(Strings.toString(boolQuery)); AbstractQueryBuilder.setMaxNestedDepth(maxDepth); try { // no errors, we reached the limit but we did not go beyond it query.rewrite(createSearchExecutionContext()); // one more level causes an exception WrapperQueryBuilder q = new WrapperQueryBuilder(Strings.toString(boolQueryBuilderTests.createQueryWithInnerQuery(boolQuery))); IllegalArgumentException e = expectThrows(XContentParseException.class, () -> q.rewrite(createSearchExecutionContext())); // there may be nested XContentParseExceptions coming from ObjectParser, we just extract the root cause while (e.getCause() != null) { assertThat(e.getCause(), Matchers.instanceOf(IllegalArgumentException.class)); e = (IllegalArgumentException) e.getCause(); } assertEquals( "The nested depth of the query exceeds the maximum nested depth for queries set in [" + INDICES_MAX_NESTED_DEPTH_SETTING.getKey() + "]", e.getMessage() ); } finally { AbstractQueryBuilder.setMaxNestedDepth(INDICES_MAX_NESTED_DEPTH_SETTING.getDefault(Settings.EMPTY)); } } }
WrapperQueryBuilderTests
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/inheritance/basic/Person.java
{ "start": 240, "end": 442 }
class ____ extends AbstractEntity<String> { private String name; protected Person() { } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Person
java
apache__camel
components/camel-coap/src/test/java/org/apache/camel/coap/CoAPRestComponentTCPTest.java
{ "start": 1201, "end": 1878 }
class ____ extends CoAPRestComponentTestBase { @Override protected String getProtocol() { return "coap+tcp"; } @Override protected void decorateClient(CoapClient client) { Configuration config = Configuration.createStandardWithoutFile(); TcpClientConnector tcpConnector = new TcpClientConnector(config); CoapEndpoint.Builder tcpBuilder = new CoapEndpoint.Builder(); tcpBuilder.setConnector(tcpConnector); client.setEndpoint(tcpBuilder.build()); } @Override protected void decorateRestConfiguration(RestConfigurationDefinition restConfig) { // Nothing here } }
CoAPRestComponentTCPTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/metrics/dump/MetricDumpSerialization.java
{ "start": 5219, "end": 14386 }
class ____ { private DataOutputSerializer countersBuffer = new DataOutputSerializer(1024 * 8); private DataOutputSerializer gaugesBuffer = new DataOutputSerializer(1024 * 8); private DataOutputSerializer metersBuffer = new DataOutputSerializer(1024 * 8); private DataOutputSerializer histogramsBuffer = new DataOutputSerializer(1024 * 8); /** * Serializes the given metrics and returns the resulting byte array. * * <p>Should a {@link Metric} accessed in this method throw an exception it will be omitted * from the returned {@link MetricSerializationResult}. * * <p>If the serialization of any primitive or String fails then the returned {@link * MetricSerializationResult} is partially corrupted. Such a result can be deserialized * safely by {@link MetricDumpDeserializer#deserialize(MetricSerializationResult)}; however * only metrics that were fully serialized before the failure will be returned. * * @param counters counters to serialize * @param gauges gauges to serialize * @param histograms histograms to serialize * @return MetricSerializationResult containing the serialized metrics and the count of each * metric type */ public MetricSerializationResult serialize( Map<Counter, Tuple2<QueryScopeInfo, String>> counters, Map<Gauge<?>, Tuple2<QueryScopeInfo, String>> gauges, Map<Histogram, Tuple2<QueryScopeInfo, String>> histograms, Map<Meter, Tuple2<QueryScopeInfo, String>> meters) { countersBuffer.clear(); int numCounters = 0; for (Map.Entry<Counter, Tuple2<QueryScopeInfo, String>> entry : counters.entrySet()) { try { serializeCounter( countersBuffer, entry.getValue().f0, entry.getValue().f1, entry.getKey()); numCounters++; } catch (Exception e) { LOG.debug("Failed to serialize counter.", e); } } gaugesBuffer.clear(); int numGauges = 0; for (Map.Entry<Gauge<?>, Tuple2<QueryScopeInfo, String>> entry : gauges.entrySet()) { try { serializeGauge( gaugesBuffer, entry.getValue().f0, entry.getValue().f1, entry.getKey()); numGauges++; } catch (Exception e) { LOG.debug("Failed to serialize gauge.", e); } } histogramsBuffer.clear(); int numHistograms = 0; for (Map.Entry<Histogram, Tuple2<QueryScopeInfo, String>> entry : histograms.entrySet()) { try { serializeHistogram( histogramsBuffer, entry.getValue().f0, entry.getValue().f1, entry.getKey()); numHistograms++; } catch (Exception e) { LOG.debug("Failed to serialize histogram.", e); } } metersBuffer.clear(); int numMeters = 0; for (Map.Entry<Meter, Tuple2<QueryScopeInfo, String>> entry : meters.entrySet()) { try { serializeMeter( metersBuffer, entry.getValue().f0, entry.getValue().f1, entry.getKey()); numMeters++; } catch (Exception e) { LOG.debug("Failed to serialize meter.", e); } } return new MetricSerializationResult( countersBuffer.getCopyOfBuffer(), gaugesBuffer.getCopyOfBuffer(), metersBuffer.getCopyOfBuffer(), histogramsBuffer.getCopyOfBuffer(), numCounters, numGauges, numMeters, numHistograms); } public void close() { countersBuffer = null; gaugesBuffer = null; metersBuffer = null; histogramsBuffer = null; } } private static void serializeMetricInfo(DataOutput out, QueryScopeInfo info) throws IOException { out.writeUTF(info.scope); out.writeByte(info.getCategory()); switch (info.getCategory()) { case INFO_CATEGORY_JM: break; case INFO_CATEGORY_TM: String tmID = ((QueryScopeInfo.TaskManagerQueryScopeInfo) info).taskManagerID; out.writeUTF(tmID); break; case INFO_CATEGORY_JOB: QueryScopeInfo.JobQueryScopeInfo jobInfo = (QueryScopeInfo.JobQueryScopeInfo) info; out.writeUTF(jobInfo.jobID); break; case INFO_CATEGORY_TASK: QueryScopeInfo.TaskQueryScopeInfo taskInfo = (QueryScopeInfo.TaskQueryScopeInfo) info; out.writeUTF(taskInfo.jobID); out.writeUTF(taskInfo.vertexID); out.writeInt(taskInfo.subtaskIndex); out.writeInt(taskInfo.attemptNumber); break; case INFO_CATEGORY_OPERATOR: QueryScopeInfo.OperatorQueryScopeInfo operatorInfo = (QueryScopeInfo.OperatorQueryScopeInfo) info; out.writeUTF(operatorInfo.jobID); out.writeUTF(operatorInfo.vertexID); out.writeInt(operatorInfo.subtaskIndex); out.writeInt(operatorInfo.attemptNumber); out.writeUTF(operatorInfo.operatorName); break; case INFO_CATEGORY_JM_OPERATOR: QueryScopeInfo.JobManagerOperatorQueryScopeInfo jmOperatorInfo = (QueryScopeInfo.JobManagerOperatorQueryScopeInfo) info; out.writeUTF(jmOperatorInfo.jobID); out.writeUTF(jmOperatorInfo.vertexID); out.writeUTF(jmOperatorInfo.operatorName); break; default: throw new IOException("Unknown scope category: " + info.getCategory()); } } private static void serializeCounter( DataOutput out, QueryScopeInfo info, String name, Counter counter) throws IOException { long count = counter.getCount(); serializeMetricInfo(out, info); out.writeUTF(name); out.writeLong(count); } private static void serializeGauge( DataOutput out, QueryScopeInfo info, String name, Gauge<?> gauge) throws IOException { Object value = gauge.getValue(); if (value == null) { throw new NullPointerException("Value returned by gauge " + name + " was null."); } String stringValue = value.toString(); if (stringValue == null) { throw new NullPointerException( "toString() of the value returned by gauge " + name + " returned null."); } serializeMetricInfo(out, info); out.writeUTF(name); out.writeUTF(stringValue); } private static void serializeHistogram( DataOutput out, QueryScopeInfo info, String name, Histogram histogram) throws IOException { HistogramStatistics stat = histogram.getStatistics(); long min = stat.getMin(); long max = stat.getMax(); double mean = stat.getMean(); double median = stat.getQuantile(0.5); double stddev = stat.getStdDev(); double p75 = stat.getQuantile(0.75); double p90 = stat.getQuantile(0.90); double p95 = stat.getQuantile(0.95); double p98 = stat.getQuantile(0.98); double p99 = stat.getQuantile(0.99); double p999 = stat.getQuantile(0.999); serializeMetricInfo(out, info); out.writeUTF(name); out.writeLong(min); out.writeLong(max); out.writeDouble(mean); out.writeDouble(median); out.writeDouble(stddev); out.writeDouble(p75); out.writeDouble(p90); out.writeDouble(p95); out.writeDouble(p98); out.writeDouble(p99); out.writeDouble(p999); } private static void serializeMeter( DataOutput out, QueryScopeInfo info, String name, Meter meter) throws IOException { serializeMetricInfo(out, info); out.writeUTF(name); out.writeDouble(meter.getRate()); } // ------------------------------------------------------------------------- // Deserialization // ------------------------------------------------------------------------- /** * Deserializer for reading a list of {@link MetricDump MetricDumps} from a {@link * MetricSerializationResult}. */ public static
MetricDumpSerializer
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/subclassmapping/fixture/SubSourceOther.java
{ "start": 211, "end": 500 }
class ____ extends ImplementedParentSource implements InterfaceParentSource { private final String finalValue; public SubSourceOther(String finalValue) { this.finalValue = finalValue; } public String getFinalValue() { return finalValue; } }
SubSourceOther
java
apache__kafka
streams/examples/src/main/java/org/apache/kafka/streams/examples/pageview/PageViewTypedDemo.java
{ "start": 6637, "end": 6804 }
class ____ implements JSONSerdeCompatible { public String user; public String page; public String region; } public static
PageViewByRegion
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/converters/HttpConverterRegistrar.java
{ "start": 1260, "end": 3492 }
class ____ implements TypeConverterRegistrar { private final BeanProvider<ResourceResolver> resourceResolver; /** * Default constructor. * * @param resourceResolver The resource resolver */ @Inject protected HttpConverterRegistrar(BeanProvider<ResourceResolver> resourceResolver) { this.resourceResolver = resourceResolver; } /** * The constructor. * * @param resourceResolver The resource resolver * @deprecated Replaced by {@link #HttpConverterRegistrar(BeanProvider)}. */ @Deprecated(forRemoval = true) protected HttpConverterRegistrar(Provider<ResourceResolver> resourceResolver) { this.resourceResolver = new BeanProvider<>() { @Override public ResourceResolver get() { return resourceResolver.get(); } }; } @Override public void register(MutableConversionService conversionService) { conversionService.addConverter( CharSequence.class, Readable.class, (object, targetType, context) -> { String pathStr = object.toString(); Optional<ResourceLoader> supportingLoader = resourceResolver.get().getSupportingLoader(pathStr); if (supportingLoader.isEmpty()) { context.reject(pathStr, new ConfigurationException( "No supported resource loader for path [" + pathStr + "]. Prefix the path with a supported prefix such as 'classpath:' or 'file:'" )); return Optional.empty(); } else { final Optional<URL> resource = resourceResolver.get().getResource(pathStr); if (resource.isPresent()) { return Optional.of(Readable.of(resource.get())); } else { context.reject(object, new ConfigurationException("No resource exists for value: " + object)); return Optional.empty(); } } } ); } }
HttpConverterRegistrar
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/permission/AclEntry.java
{ "start": 1634, "end": 4178 }
class ____ { private final AclEntryType type; private final String name; private final FsAction permission; private final AclEntryScope scope; /** * Returns the ACL entry type. * * @return AclEntryType ACL entry type */ public AclEntryType getType() { return type; } /** * Returns the optional ACL entry name. * * @return String ACL entry name, or null if undefined */ public String getName() { return name; } /** * Returns the set of permissions in the ACL entry. * * @return FsAction set of permissions in the ACL entry */ public FsAction getPermission() { return permission; } /** * Returns the scope of the ACL entry. * * @return AclEntryScope scope of the ACL entry */ public AclEntryScope getScope() { return scope; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (getClass() != o.getClass()) { return false; } AclEntry other = (AclEntry)o; return Objects.equal(type, other.type) && Objects.equal(name, other.name) && Objects.equal(permission, other.permission) && Objects.equal(scope, other.scope); } @Override public int hashCode() { return Objects.hashCode(type, name, permission, scope); } @Override @InterfaceStability.Unstable public String toString() { // This currently just delegates to the stable string representation, but it // is permissible for the output of this method to change across versions. return toStringStable(); } /** * Returns a string representation guaranteed to be stable across versions to * satisfy backward compatibility requirements, such as for shell command * output or serialization. The format of this string representation matches * what is expected by the {@link #parseAclSpec(String, boolean)} and * {@link #parseAclEntry(String, boolean)} methods. * * @return stable, backward compatible string representation */ public String toStringStable() { StringBuilder sb = new StringBuilder(); if (scope == AclEntryScope.DEFAULT) { sb.append("default:"); } if (type != null) { sb.append(StringUtils.toLowerCase(type.toStringStable())); } sb.append(':'); if (name != null) { sb.append(name); } sb.append(':'); if (permission != null) { sb.append(permission.SYMBOL); } return sb.toString(); } /** * Builder for creating new AclEntry instances. */ public static
AclEntry
java
spring-projects__spring-boot
module/spring-boot-micrometer-observation/src/main/java/org/springframework/boot/micrometer/observation/autoconfigure/ScheduledTasksObservationAutoConfiguration.java
{ "start": 1896, "end": 2323 }
class ____ implements SchedulingConfigurer { private final ObservationRegistry observationRegistry; ObservabilitySchedulingConfigurer(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setObservationRegistry(this.observationRegistry); } } }
ObservabilitySchedulingConfigurer
java
quarkusio__quarkus
integration-tests/redis-devservices/src/test/java/io/quarkus/redis/devservices/it/DevServicesRedisNonUniquePortTest.java
{ "start": 577, "end": 1474 }
class ____ { @Inject RedisDataSource redisClient; @BeforeEach public void setUp() { redisClient.value(String.class).set("anykey", "anyvalue"); } @Test @DisplayName("given redis container must communicate with it and return value by key") public void shouldReturnAllKeys() { Assertions.assertEquals("anyvalue", redisClient.value(String.class).get("anykey").toString()); } @Test public void shouldHaveStack() { // The entertainingly named lolwut command gives a version number but doesn't say if stack is available, so try using some of the commands try { redisClient.bloom(String.class).bfadd("key", "whatever"); } catch (Exception e) { fail("Redis stack should be available on the connected back end (underlying error was " + e + ")"); } } }
DevServicesRedisNonUniquePortTest
java
apache__rocketmq
store/src/main/java/org/apache/rocketmq/store/DispatchRequest.java
{ "start": 1011, "end": 7317 }
class ____ { private final String topic; private final int queueId; private final long commitLogOffset; private int msgSize; private final long tagsCode; private final long storeTimestamp; private final long consumeQueueOffset; private final String keys; private final boolean success; private final String uniqKey; private final int sysFlag; private final long preparedTransactionOffset; private final Map<String, String> propertiesMap; private byte[] bitMap; private int bufferSize = -1;//the buffer size maybe larger than the msg size if the message is wrapped by something // for batch consume queue private long msgBaseOffset = -1; private short batchSize = 1; private long nextReputFromOffset = -1; private String offsetId; public DispatchRequest( final String topic, final int queueId, final long commitLogOffset, final int msgSize, final long tagsCode, final long storeTimestamp, final long consumeQueueOffset, final String keys, final String uniqKey, final int sysFlag, final long preparedTransactionOffset, final Map<String, String> propertiesMap ) { this.topic = topic; this.queueId = queueId; this.commitLogOffset = commitLogOffset; this.msgSize = msgSize; this.tagsCode = tagsCode; this.storeTimestamp = storeTimestamp; this.consumeQueueOffset = consumeQueueOffset; this.msgBaseOffset = consumeQueueOffset; this.keys = keys; this.uniqKey = uniqKey; this.sysFlag = sysFlag; this.preparedTransactionOffset = preparedTransactionOffset; this.success = true; this.propertiesMap = propertiesMap; } public DispatchRequest(String topic, int queueId, long consumeQueueOffset, long commitLogOffset, int size, long tagsCode) { this.topic = topic; this.queueId = queueId; this.commitLogOffset = commitLogOffset; this.msgSize = size; this.tagsCode = tagsCode; this.storeTimestamp = 0; this.consumeQueueOffset = consumeQueueOffset; this.keys = ""; this.uniqKey = null; this.sysFlag = 0; this.preparedTransactionOffset = 0; this.success = false; this.propertiesMap = null; } public DispatchRequest(int size) { this.topic = ""; this.queueId = 0; this.commitLogOffset = 0; this.msgSize = size; this.tagsCode = 0; this.storeTimestamp = 0; this.consumeQueueOffset = 0; this.keys = ""; this.uniqKey = null; this.sysFlag = 0; this.preparedTransactionOffset = 0; this.success = false; this.propertiesMap = null; } public DispatchRequest(int size, boolean success) { this.topic = ""; this.queueId = 0; this.commitLogOffset = 0; this.msgSize = size; this.tagsCode = 0; this.storeTimestamp = 0; this.consumeQueueOffset = 0; this.keys = ""; this.uniqKey = null; this.sysFlag = 0; this.preparedTransactionOffset = 0; this.success = success; this.propertiesMap = null; } public String getTopic() { return topic; } public int getQueueId() { return queueId; } public long getCommitLogOffset() { return commitLogOffset; } public int getMsgSize() { return msgSize; } public long getStoreTimestamp() { return storeTimestamp; } public long getConsumeQueueOffset() { return consumeQueueOffset; } public String getKeys() { return keys; } public long getTagsCode() { return tagsCode; } public int getSysFlag() { return sysFlag; } public long getPreparedTransactionOffset() { return preparedTransactionOffset; } public boolean isSuccess() { return success; } public String getUniqKey() { return uniqKey; } public Map<String, String> getPropertiesMap() { return propertiesMap; } public byte[] getBitMap() { return bitMap; } public void setBitMap(byte[] bitMap) { this.bitMap = bitMap; } public short getBatchSize() { return batchSize; } public void setBatchSize(short batchSize) { this.batchSize = batchSize; } public void setMsgSize(int msgSize) { this.msgSize = msgSize; } public long getMsgBaseOffset() { return msgBaseOffset; } public void setMsgBaseOffset(long msgBaseOffset) { this.msgBaseOffset = msgBaseOffset; } public int getBufferSize() { return bufferSize; } public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } public long getNextReputFromOffset() { return nextReputFromOffset; } public void setNextReputFromOffset(long nextReputFromOffset) { this.nextReputFromOffset = nextReputFromOffset; } public String getOffsetId() { return offsetId; } public void setOffsetId(String offsetId) { this.offsetId = offsetId; } public boolean containsLMQ() { if (!MixAll.topicAllowsLMQ(topic)) { return false; } if (null == propertiesMap || propertiesMap.isEmpty()) { return false; } String lmqNames = propertiesMap.get(MessageConst.PROPERTY_INNER_MULTI_DISPATCH); String lmqOffsets = propertiesMap.get(MessageConst.PROPERTY_INNER_MULTI_QUEUE_OFFSET); return !StringUtils.isBlank(lmqNames) && !StringUtils.isBlank(lmqOffsets); } @Override public String toString() { return "DispatchRequest{" + "topic='" + topic + '\'' + ", queueId=" + queueId + ", commitLogOffset=" + commitLogOffset + ", msgSize=" + msgSize + ", success=" + success + ", msgBaseOffset=" + msgBaseOffset + ", batchSize=" + batchSize + ", nextReputFromOffset=" + nextReputFromOffset + '}'; } }
DispatchRequest
java
apache__flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/source/datagen/DataGeneratorSource.java
{ "start": 1675, "end": 5134 }
class ____<T> extends RichParallelSourceFunction<T> implements CheckpointedFunction { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(DataGeneratorSource.class); private final DataGenerator<T> generator; private final long rowsPerSecond; @Nullable private final Long numberOfRows; private transient int outputSoFar; private transient int toOutput; transient volatile boolean isRunning; /** * Creates a source that emits records by {@link DataGenerator} without controlling emit rate. * * @param generator data generator. */ public DataGeneratorSource(DataGenerator<T> generator) { this(generator, Long.MAX_VALUE, null); } /** * Creates a source that emits records by {@link DataGenerator}. * * @param generator data generator. * @param rowsPerSecond Control the emit rate. * @param numberOfRows Total number of rows to output. */ public DataGeneratorSource( DataGenerator<T> generator, long rowsPerSecond, @Nullable Long numberOfRows) { this.generator = generator; this.rowsPerSecond = rowsPerSecond; this.numberOfRows = numberOfRows; } @Override public void open(OpenContext openContext) throws Exception { super.open(openContext); if (numberOfRows != null) { final int stepSize = getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks(); final int taskIdx = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(); final int baseSize = (int) (numberOfRows / stepSize); toOutput = (numberOfRows % stepSize > taskIdx) ? baseSize + 1 : baseSize; } } @Override public void initializeState(FunctionInitializationContext context) throws Exception { this.generator.open("DataGenerator", context, getRuntimeContext()); this.isRunning = true; } @Override public void snapshotState(FunctionSnapshotContext context) throws Exception { this.generator.snapshotState(context); } @Override public void run(SourceContext<T> ctx) throws Exception { double taskRowsPerSecond = (double) rowsPerSecond / getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks(); long nextReadTime = System.currentTimeMillis(); while (isRunning) { for (int i = 0; i < taskRowsPerSecond; i++) { if (isRunning && generator.hasNext() && (numberOfRows == null || outputSoFar < toOutput)) { synchronized (ctx.getCheckpointLock()) { outputSoFar++; ctx.collect(this.generator.next()); } } else { return; } } nextReadTime += 1000; long toWaitMs = nextReadTime - System.currentTimeMillis(); while (toWaitMs > 0) { Thread.sleep(toWaitMs); toWaitMs = nextReadTime - System.currentTimeMillis(); } } } @Override public void close() throws Exception { super.close(); LOG.info("generated {} rows", outputSoFar); } @Override public void cancel() { isRunning = false; } }
DataGeneratorSource
java
apache__camel
components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisSelectOneExchangeInOutWithOutputHeaderTest.java
{ "start": 1093, "end": 2522 }
class ____ extends MyBatisTestSupport { private static final String TEST_CASE_HEADER_NAME = "testCaseHeader"; private static final int TEST_ACCOUNT_ID = 456; @Test public void testSelectOneWithOutputHeader() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.message(0).header(TEST_CASE_HEADER_NAME).isInstanceOf(Account.class); mock.message(0).body().isEqualTo(TEST_ACCOUNT_ID); mock.message(0).header(MyBatisConstants.MYBATIS_RESULT).isNull(); template.sendBody("direct:start", TEST_ACCOUNT_ID); MockEndpoint.assertIsSatisfied(context); Account account = mock.getReceivedExchanges().get(0).getIn().getHeader(TEST_CASE_HEADER_NAME, Account.class); assertEquals("Claus", account.getFirstName()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // START SNIPPET: e1 from("direct:start") .setExchangePattern(ExchangePattern.InOut) .to("mybatis:selectAccountById?statementType=SelectOne&outputHeader=" + TEST_CASE_HEADER_NAME) .to("mock:result"); // END SNIPPET: e1 } }; } }
MyBatisSelectOneExchangeInOutWithOutputHeaderTest
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/ForecastJobAction.java
{ "start": 7953, "end": 9772 }
class ____ extends BaseTasksResponse implements Writeable, ToXContentObject { private final boolean acknowledged; private final String forecastId; public Response(boolean acknowledged, String forecastId) { super(null, null); this.acknowledged = acknowledged; this.forecastId = forecastId; } public Response(StreamInput in) throws IOException { super(in); acknowledged = in.readBoolean(); forecastId = in.readString(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBoolean(acknowledged); out.writeString(forecastId); } public boolean isAcknowledged() { return acknowledged; } public String getForecastId() { return forecastId; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("acknowledged", acknowledged); builder.field(Forecast.FORECAST_ID.getPreferredName(), forecastId); builder.endObject(); return builder; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Response other = (Response) obj; return this.acknowledged == other.acknowledged && Objects.equals(this.forecastId, other.forecastId); } @Override public int hashCode() { return Objects.hash(acknowledged, forecastId); } } }
Response
java
alibaba__fastjson
src/main/java/com/alibaba/fastjson/JSONPath.java
{ "start": 101157, "end": 102126 }
class ____ extends PropertyFilter { private final long[] values; private final boolean not; public IntInSegement(String propertyName, boolean function, long[] values, boolean not){ super(propertyName, function); this.values = values; this.not = not; } public boolean apply(JSONPath path, Object rootObject, Object currentObject, Object item) { Object propertyValue = get(path, rootObject, item); if (propertyValue == null) { return false; } if (propertyValue instanceof Number) { long longPropertyValue = TypeUtils.longExtractValue((Number) propertyValue); for (long value : values) { if (value == longPropertyValue) { return !not; } } } return not; } } static
IntInSegement
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/ActiveResult.java
{ "start": 345, "end": 2953 }
class ____ { private static final ActiveResult ACTIVE = new ActiveResult(true, null, null); private final boolean value; private final String inactiveReason; private final ActiveResult inactiveCause; /** * The synthetic bean in question is active. * * @return the active result */ public static ActiveResult active() { return ACTIVE; } /** * The synthetic bean is question is inactive for given {@code reason}. * * @param reason the reason why the synthetic bean is inactive; must not be {@code null} * @return the inactive result */ public static ActiveResult inactive(String reason) { return new ActiveResult(false, Objects.requireNonNull(reason), null); } /** * The synthetic bean is question is inactive for given {@code reason}. * The given {@code cause} is an {@link ActiveResult} for an underlying bean * that is inactive and causes this bean to also become inactive. * * @param reason the reason why the synthetic bean is inactive; must not be {@code null} * @param cause the cause why the synthetic bean is inactive; may be {@code null}, * but when it is not, it must be inactive as well * @return the inactive result with a cause */ public static ActiveResult inactive(String reason, ActiveResult cause) { if (cause != null && cause.value) { throw new IllegalArgumentException("The cause of an inactive result must also be inactive"); } return new ActiveResult(false, Objects.requireNonNull(reason), cause); } private ActiveResult(boolean value, String inactiveReason, ActiveResult inactiveCause) { this.value = value; this.inactiveReason = inactiveReason; this.inactiveCause = inactiveCause; } /** * Returns whether the synthetic bean in question is active. * * @return whether the synthetic bean in question is active */ public boolean value() { return value; } /** * Returns the reason why the synthetic bean is not active. * Returns {@code null} only if the synthetic bean is active. * * @return the reason why the synthetic bean is not active */ public String inactiveReason() { return inactiveReason; } /** * Returns the cause of why the synthetic bean is not active. * * @return the cause of why the synthetic bean is not active; may be {@code null} */ public ActiveResult inactiveCause() { return inactiveCause; } }
ActiveResult
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/constants/InternalConstants.java
{ "start": 1107, "end": 1602 }
class ____ { private InternalConstants() { } /** * Does this version of the store have safe readahead? * Possible combinations of this and the probe * {@code "fs.capability.etags.available"}. * <ol> * <li>{@value}: store is safe</li> * <li>no etags: store is safe</li> * <li>etags and not {@value}: store is <i>UNSAFE</i></li> * </ol> */ public static final String CAPABILITY_SAFE_READAHEAD = "fs.azure.capability.readahead.safe"; }
InternalConstants
java
google__guice
core/src/com/google/inject/internal/MoreTypes.java
{ "start": 16951, "end": 17834 }
class ____ implements GenericArrayType, Serializable, CompositeType { private final Type componentType; public GenericArrayTypeImpl(Type componentType) { this.componentType = canonicalize(componentType); } @Override public Type getGenericComponentType() { return componentType; } @Override public boolean isFullySpecified() { return MoreTypes.isFullySpecified(componentType); } @Override public boolean equals(Object o) { return o instanceof GenericArrayType && MoreTypes.equals(this, (GenericArrayType) o); } @Override public int hashCode() { return componentType.hashCode(); } @Override public String toString() { return typeToString(componentType) + "[]"; } private static final long serialVersionUID = 0; } /** * The WildcardType
GenericArrayTypeImpl
java
spring-projects__spring-boot
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/actuator/observability/opentelemetry/environmentvariables/AutoConfiguredOpenTelemetrySdkConfiguration.java
{ "start": 997, "end": 1189 }
class ____ { @Bean OpenTelemetry autoConfiguredOpenTelemetrySdk() { return AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk(); } }
AutoConfiguredOpenTelemetrySdkConfiguration
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java
{ "start": 2011, "end": 3424 }
class ____ extends AbstractBeanDefinition { private @Nullable String parentName; /** * Create a new ChildBeanDefinition for the given parent, to be * configured through its bean properties and configuration methods. * @param parentName the name of the parent bean * @see #setBeanClass * @see #setScope * @see #setConstructorArgumentValues * @see #setPropertyValues */ public ChildBeanDefinition(String parentName) { super(); this.parentName = parentName; } /** * Create a new ChildBeanDefinition for the given parent. * @param parentName the name of the parent bean * @param pvs the additional property values of the child */ public ChildBeanDefinition(String parentName, MutablePropertyValues pvs) { super(null, pvs); this.parentName = parentName; } /** * Create a new ChildBeanDefinition for the given parent. * @param parentName the name of the parent bean * @param cargs the constructor argument values to apply * @param pvs the additional property values of the child */ public ChildBeanDefinition( String parentName, ConstructorArgumentValues cargs, MutablePropertyValues pvs) { super(cargs, pvs); this.parentName = parentName; } /** * Create a new ChildBeanDefinition for the given parent, * providing constructor arguments and property values. * @param parentName the name of the parent bean * @param beanClass the
ChildBeanDefinition
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/CrossOriginTests.java
{ "start": 21414, "end": 21846 }
class ____ { @RequestMapping(path = "/foo", method = RequestMethod.GET) public void foo() { } @CrossOrigin @RequestMapping(path = "/bar", method = RequestMethod.GET) public void bar() { } @CrossOrigin(originPatterns = "*", allowCredentials = "true") @RequestMapping(path = "/baz", method = RequestMethod.GET) public void baz() { } } @Controller @CrossOrigin(maxAge = 10) private static
ClassLevelController
java
apache__rocketmq
openmessaging/src/main/java/io/openmessaging/rocketmq/producer/AbstractOMSProducer.java
{ "start": 2001, "end": 6593 }
class ____ implements ServiceLifecycle, MessageFactory { final KeyValue properties; final DefaultMQProducer rocketmqProducer; private boolean started = false; private final ClientConfig clientConfig; AbstractOMSProducer(final KeyValue properties) { this.properties = properties; this.rocketmqProducer = new DefaultMQProducer(); this.clientConfig = BeanUtils.populate(properties, ClientConfig.class); if ("true".equalsIgnoreCase(System.getenv("OMS_RMQ_DIRECT_NAME_SRV"))) { String accessPoints = clientConfig.getAccessPoints(); if (accessPoints == null || accessPoints.isEmpty()) { throw new OMSRuntimeException("-1", "OMS AccessPoints is null or empty."); } this.rocketmqProducer.setNamesrvAddr(accessPoints.replace(',', ';')); } this.rocketmqProducer.setProducerGroup(clientConfig.getRmqProducerGroup()); String producerId = buildInstanceName(); this.rocketmqProducer.setSendMsgTimeout(clientConfig.getOperationTimeout()); this.rocketmqProducer.setInstanceName(producerId); this.rocketmqProducer.setMaxMessageSize(1024 * 1024 * 4); this.rocketmqProducer.setLanguage(LanguageCode.OMS); properties.put(OMSBuiltinKeys.PRODUCER_ID, producerId); } @Override public synchronized void startup() { if (!started) { try { this.rocketmqProducer.start(); } catch (MQClientException e) { throw new OMSRuntimeException("-1", e); } } this.started = true; } @Override public synchronized void shutdown() { if (this.started) { this.rocketmqProducer.shutdown(); } this.started = false; } OMSRuntimeException checkProducerException(String topic, String msgId, Throwable e) { if (e instanceof MQClientException) { if (e.getCause() != null) { if (e.getCause() instanceof RemotingTimeoutException) { return new OMSTimeOutException("-1", String.format("Send message to broker timeout, %dms, Topic=%s, msgId=%s", this.rocketmqProducer.getSendMsgTimeout(), topic, msgId), e); } else if (e.getCause() instanceof MQBrokerException || e.getCause() instanceof RemotingConnectException) { if (e.getCause() instanceof MQBrokerException) { MQBrokerException brokerException = (MQBrokerException) e.getCause(); return new OMSRuntimeException("-1", String.format("Received a broker exception, Topic=%s, msgId=%s, %s", topic, msgId, brokerException.getErrorMessage()), e); } if (e.getCause() instanceof RemotingConnectException) { RemotingConnectException connectException = (RemotingConnectException)e.getCause(); return new OMSRuntimeException("-1", String.format("Network connection experiences failures. Topic=%s, msgId=%s, %s", topic, msgId, connectException.getMessage()), e); } } } // Exception thrown by local. else { MQClientException clientException = (MQClientException) e; if (-1 == clientException.getResponseCode()) { return new OMSRuntimeException("-1", String.format("Topic does not exist, Topic=%s, msgId=%s", topic, msgId), e); } else if (ResponseCode.MESSAGE_ILLEGAL == clientException.getResponseCode()) { return new OMSMessageFormatException("-1", String.format("A illegal message for RocketMQ, Topic=%s, msgId=%s", topic, msgId), e); } } } return new OMSRuntimeException("-1", "Send message to RocketMQ broker failed.", e); } protected void checkMessageType(Message message) { if (!(message instanceof BytesMessage)) { throw new OMSNotSupportedException("-1", "Only BytesMessage is supported."); } } @Override public BytesMessage createBytesMessage(String queue, byte[] body) { BytesMessage message = new BytesMessageImpl(); message.setBody(body); message.sysHeaders().put(Message.BuiltinKeys.DESTINATION, queue); return message; } }
AbstractOMSProducer
java
apache__camel
test-infra/camel-test-infra-weaviate/src/test/java/org/apache/camel/test/infra/weaviate/services/WeaviateServiceFactory.java
{ "start": 2360, "end": 2493 }
class ____ extends WeaviateLocalContainerInfraService implements WeaviateService { } public static
WeaviateLocalContainerService
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/enums/EnumDeserilizationFeatureOrderTest.java
{ "start": 541, "end": 833 }
class ____ extends DatabindTestUtil { /* /********************************************************** /* Set up /********************************************************** */ private final ObjectMapper MAPPER = newJsonMapper();
EnumDeserilizationFeatureOrderTest
java
apache__dubbo
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationClusterInvoker.java
{ "start": 1171, "end": 1706 }
interface ____<T> extends ClusterInvoker<T> { @Override boolean isServiceDiscovery(); MigrationStep getMigrationStep(); void setMigrationStep(MigrationStep step); MigrationRule getMigrationRule(); void setMigrationRule(MigrationRule rule); boolean migrateToForceInterfaceInvoker(MigrationRule newRule); boolean migrateToForceApplicationInvoker(MigrationRule newRule); void migrateToApplicationFirstInvoker(MigrationRule newRule); void reRefer(URL newSubscribeUrl); }
MigrationClusterInvoker
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/cli/CLITestCmdDFS.java
{ "start": 1195, "end": 1596 }
class ____ extends CLITestCmd { public CLITestCmdDFS(String str, CLICommandTypes type) { super(str, type); } @Override public CommandExecutor getExecutor(String tag, Configuration conf) throws IllegalArgumentException { if (getType() instanceof CLICommandDFSAdmin) return new FSCmdExecutor(tag, new DFSAdmin(conf)); return super.getExecutor(tag, conf); } }
CLITestCmdDFS
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteProcessor.java
{ "start": 1691, "end": 10343 }
class ____<T> implements Processor<T, Void> { /** * Special logger for debugging Reactive Streams signals. * @see LogDelegateFactory#getHiddenLog(Class) * @see AbstractListenerReadPublisher#rsReadLogger * @see AbstractListenerWriteFlushProcessor#rsWriteFlushLogger * @see WriteResultPublisher#rsWriteResultLogger */ protected static final Log rsWriteLogger = LogDelegateFactory.getHiddenLog(AbstractListenerWriteProcessor.class); private final AtomicReference<State> state = new AtomicReference<>(State.UNSUBSCRIBED); private @Nullable Subscription subscription; private volatile @Nullable T currentData; /* Indicates "onComplete" was received during the (last) write. */ private volatile boolean sourceCompleted; /** * Indicates we're waiting for one last isReady-onWritePossible cycle * after "onComplete" because some Servlet containers expect this to take * place prior to calling AsyncContext.complete(). * @see <a href="https://github.com/jakartaee/servlet/issues/273">Jakarta Servlet issue 273</a> */ private volatile boolean readyToCompleteAfterLastWrite; private final WriteResultPublisher resultPublisher; private final String logPrefix; public AbstractListenerWriteProcessor() { this(""); } /** * Create an instance with the given log prefix. * @since 5.1 */ public AbstractListenerWriteProcessor(String logPrefix) { // AbstractListenerFlushProcessor calls cancelAndSetCompleted directly, so this cancel task // won't be used for HTTP responses, but it can be for a WebSocket session. this.resultPublisher = new WriteResultPublisher(logPrefix + "[WP] ", this::cancelAndSetCompleted); this.logPrefix = (StringUtils.hasText(logPrefix) ? logPrefix : ""); } /** * Get the configured log prefix. * @since 5.1 */ public String getLogPrefix() { return this.logPrefix; } // Subscriber methods and async I/O notification methods... @Override public final void onSubscribe(Subscription subscription) { this.state.get().onSubscribe(this, subscription); } @Override public final void onNext(T data) { if (rsWriteLogger.isTraceEnabled()) { rsWriteLogger.trace(getLogPrefix() + "onNext: " + data.getClass().getSimpleName()); } this.state.get().onNext(this, data); } /** * Error signal from the upstream, write Publisher. This is also used by * subclasses to delegate error notifications from the container. */ @Override public final void onError(Throwable ex) { State state = this.state.get(); if (rsWriteLogger.isTraceEnabled()) { rsWriteLogger.trace(getLogPrefix() + "onError: " + ex + " [" + state + "]"); } state.onError(this, ex); } /** * Completion signal from the upstream, write Publisher. This is also used * by subclasses to delegate completion notifications from the container. */ @Override public final void onComplete() { State state = this.state.get(); if (rsWriteLogger.isTraceEnabled()) { rsWriteLogger.trace(getLogPrefix() + "onComplete [" + state + "]"); } state.onComplete(this); } /** * Invoked when writing is possible, either in the same thread after a check * via {@link #isWritePossible()}, or as a callback from the underlying * container. */ public final void onWritePossible() { State state = this.state.get(); if (rsWriteLogger.isTraceEnabled()) { rsWriteLogger.trace(getLogPrefix() + "onWritePossible [" + state + "]"); } state.onWritePossible(this); } /** * Cancel the upstream "write" Publisher only, for example due to * Servlet container error/completion notifications. This should usually * be followed up with a call to either {@link #onError(Throwable)} or * {@link #onComplete()} to notify the downstream chain, that is unless * cancellation came from downstream. */ public void cancel() { if (rsWriteLogger.isTraceEnabled()) { rsWriteLogger.trace(getLogPrefix() + "cancel [" + this.state + "]"); } if (this.subscription != null) { this.subscription.cancel(); } } /** * Cancel the "write" Publisher and transition to COMPLETED immediately also * without notifying the downstream. For use when cancellation came from * downstream. */ void cancelAndSetCompleted() { cancel(); for (;;) { State prev = this.state.get(); if (prev == State.COMPLETED) { break; } if (this.state.compareAndSet(prev, State.COMPLETED)) { if (rsWriteLogger.isTraceEnabled()) { rsWriteLogger.trace(getLogPrefix() + prev + " -> " + this.state); } if (prev != State.WRITING) { discardCurrentData(); } break; } } } // Publisher implementation for result notifications... @Override public final void subscribe(Subscriber<? super Void> subscriber) { this.resultPublisher.subscribe(subscriber); } // Write API methods to be implemented or template methods to override... /** * Whether the given data item has any content to write. * If false the item is not written. */ protected abstract boolean isDataEmpty(T data); /** * Template method invoked after a data item to write is received via * {@link Subscriber#onNext(Object)}. The default implementation saves the * data item for writing once that is possible. */ protected void dataReceived(T data) { T prev = this.currentData; if (prev != null) { // This shouldn't happen: // 1. dataReceived can only be called from REQUESTED state // 2. currentData is cleared before requesting discardData(data); cancel(); onError(new IllegalStateException("Received new data while current not processed yet.")); } this.currentData = data; } /** * Whether writing is possible. */ protected abstract boolean isWritePossible(); /** * Write the given item. * <p><strong>Note:</strong> Sub-classes are responsible for releasing any * data buffer associated with the item, once fully written, if pooled * buffers apply to the underlying container. * @param data the item to write * @return {@code true} if the current data item was written completely and * a new item requested, or {@code false} if it was written partially and * we'll need more write callbacks before it is fully written */ protected abstract boolean write(T data) throws IOException; /** * Invoked after onComplete or onError notification. * <p>The default implementation is a no-op. */ protected void writingComplete() { } /** * Invoked when an I/O error occurs during a write. Subclasses may choose * to ignore this if they know the underlying API will provide an error * notification in a container thread. * <p>Defaults to no-op. */ protected void writingFailed(Throwable ex) { } /** * Invoked after any error (either from the upstream write Publisher, or * from I/O operations to the underlying server) and cancellation * to discard in-flight data that was in * the process of being written when the error took place. * @param data the data to be released * @since 5.0.11 */ protected abstract void discardData(T data); // Private methods for use from State's... private boolean changeState(State oldState, State newState) { boolean result = this.state.compareAndSet(oldState, newState); if (result && rsWriteLogger.isTraceEnabled()) { rsWriteLogger.trace(getLogPrefix() + oldState + " -> " + newState); } return result; } private void changeStateToReceived(State oldState) { if (changeState(oldState, State.RECEIVED)) { writeIfPossible(); } } private void changeStateToComplete(State oldState) { if (changeState(oldState, State.COMPLETED)) { discardCurrentData(); writingComplete(); this.resultPublisher.publishComplete(); } else { this.state.get().onComplete(this); } } private void writeIfPossible() { boolean result = isWritePossible(); if (!result && rsWriteLogger.isTraceEnabled()) { rsWriteLogger.trace(getLogPrefix() + "isWritePossible false"); } if (result) { onWritePossible(); } } private void discardCurrentData() { T data = this.currentData; this.currentData = null; if (data != null) { discardData(data); } } /** * Represents a state for the {@link Processor} to be in. * * <p><pre> * UNSUBSCRIBED * | * v * +--- REQUESTED -------------> RECEIVED ---+ * | ^ ^ | * | | | | * | + ------ WRITING <------+ | * | | | * | v | * +--------------> COMPLETED <--------------+ * </pre> */ private
AbstractListenerWriteProcessor
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/reader/AppStateReader.java
{ "start": 1673, "end": 2614 }
class ____ implements MessageBodyReader<AppState> { private JettisonUnmarshaller jsonUnmarshaller; public AppStateReader() { try { JettisonJaxbContext jettisonJaxbContext = new JettisonJaxbContext(AppState.class); jsonUnmarshaller = jettisonJaxbContext.createJsonUnmarshaller(); } catch (JAXBException e) { } } @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == AppState.class; } @Override public AppState readFrom(Class<AppState> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { try { return jsonUnmarshaller.unmarshalFromJSON(entityStream, AppState.class); } catch (JAXBException e) { throw new IOException(e); } } }
AppStateReader
java
grpc__grpc-java
netty/src/test/java/io/grpc/netty/UdsNameResolverTest.java
{ "start": 1514, "end": 3680 }
class ____ { @Rule public final MockitoRule mocks = MockitoJUnit.rule(); private static final int DEFAULT_PORT = 887; private final FakeClock fakeExecutor = new FakeClock(); private final SynchronizationContext syncContext = new SynchronizationContext( (t, e) -> { throw new AssertionError(e); }); private final NameResolver.Args args = NameResolver.Args.newBuilder() .setDefaultPort(DEFAULT_PORT) .setProxyDetector(GrpcUtil.DEFAULT_PROXY_DETECTOR) .setSynchronizationContext(syncContext) .setServiceConfigParser(mock(ServiceConfigParser.class)) .setChannelLogger(mock(ChannelLogger.class)) .setScheduledExecutorService(fakeExecutor.getScheduledExecutorService()) .build(); @Mock private NameResolver.Listener2 mockListener; @Captor private ArgumentCaptor<NameResolver.ResolutionResult> resultCaptor; private UdsNameResolver udsNameResolver; @Test public void testValidTargetPath() { udsNameResolver = new UdsNameResolver(null, "sock.sock", args); udsNameResolver.start(mockListener); verify(mockListener).onResult2(resultCaptor.capture()); NameResolver.ResolutionResult result = resultCaptor.getValue(); List<EquivalentAddressGroup> list = result.getAddressesOrError().getValue(); assertThat(list).isNotNull(); assertThat(list).hasSize(1); EquivalentAddressGroup eag = list.get(0); assertThat(eag).isNotNull(); List<SocketAddress> addresses = eag.getAddresses(); assertThat(addresses).hasSize(1); assertThat(addresses.get(0)).isInstanceOf(DomainSocketAddress.class); DomainSocketAddress domainSocketAddress = (DomainSocketAddress) addresses.get(0); assertThat(domainSocketAddress.path()).isEqualTo("sock.sock"); assertThat(udsNameResolver.getServiceAuthority()).isEqualTo("sock.sock"); } @Test public void testNonNullAuthority() { try { udsNameResolver = new UdsNameResolver("authority", "sock.sock", args); fail("exception expected"); } catch (IllegalArgumentException e) { assertThat(e).hasMessageThat().isEqualTo("non-null authority not supported"); } } }
UdsNameResolverTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/router/async/TestRouterAsyncCacheAdmin.java
{ "start": 1659, "end": 4082 }
class ____ extends RouterAsyncProtocolTestBase { private RouterAsyncCacheAdmin asyncCacheAdmin; @BeforeEach public void setup() throws IOException { asyncCacheAdmin = new RouterAsyncCacheAdmin(getRouterAsyncRpcServer()); FSDataOutputStream fsDataOutputStream = getRouterFs().create( new Path("/testCache.file"), true); fsDataOutputStream.write(new byte[1024]); fsDataOutputStream.close(); } @Test public void testRouterAsyncCacheAdmin() throws Exception { asyncCacheAdmin.addCachePool(new CachePoolInfo("pool")); syncReturn(null); CacheDirectiveInfo path = new CacheDirectiveInfo.Builder(). setPool("pool"). setPath(new Path("/testCache.file")). build(); asyncCacheAdmin.addCacheDirective(path, EnumSet.of(CacheFlag.FORCE)); long result = syncReturn(long.class); assertEquals(1, result); asyncCacheAdmin.listCachePools(""); BatchedEntries<CachePoolEntry> cachePoolEntries = syncReturn(BatchedEntries.class); assertEquals("pool", cachePoolEntries.get(0).getInfo().getPoolName()); CacheDirectiveInfo filter = new CacheDirectiveInfo.Builder(). setPool("pool"). build(); asyncCacheAdmin.listCacheDirectives(0, filter); BatchedEntries<CacheDirectiveEntry> cacheDirectiveEntries = syncReturn(BatchedEntries.class); assertEquals(new Path("/testCache.file"), cacheDirectiveEntries.get(0).getInfo().getPath()); CachePoolInfo pool = new CachePoolInfo("pool").setOwnerName("pool_user"); asyncCacheAdmin.modifyCachePool(pool); syncReturn(null); asyncCacheAdmin.listCachePools(""); cachePoolEntries = syncReturn(BatchedEntries.class); assertEquals("pool_user", cachePoolEntries.get(0).getInfo().getOwnerName()); path = new CacheDirectiveInfo.Builder(). setPool("pool"). setPath(new Path("/testCache.file")). setReplication((short) 2). setId(1L). build(); asyncCacheAdmin.modifyCacheDirective(path, EnumSet.of(CacheFlag.FORCE)); syncReturn(null); asyncCacheAdmin.listCacheDirectives(0, filter); cacheDirectiveEntries = syncReturn(BatchedEntries.class); assertEquals(Short.valueOf((short) 2), cacheDirectiveEntries.get(0).getInfo().getReplication()); asyncCacheAdmin.removeCacheDirective(1L); syncReturn(null); asyncCacheAdmin.removeCachePool("pool"); syncReturn(null); } }
TestRouterAsyncCacheAdmin
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/producer/ProducerRecordTest.java
{ "start": 1065, "end": 3292 }
class ____ { @Test public void testEqualsAndHashCode() { ProducerRecord<String, Integer> producerRecord = new ProducerRecord<>("test", 1, "key", 1); assertEquals(producerRecord, producerRecord); assertEquals(producerRecord.hashCode(), producerRecord.hashCode()); ProducerRecord<String, Integer> equalRecord = new ProducerRecord<>("test", 1, "key", 1); assertEquals(producerRecord, equalRecord); assertEquals(producerRecord.hashCode(), equalRecord.hashCode()); ProducerRecord<String, Integer> topicMisMatch = new ProducerRecord<>("test-1", 1, "key", 1); assertNotEquals(producerRecord, topicMisMatch); ProducerRecord<String, Integer> partitionMismatch = new ProducerRecord<>("test", 2, "key", 1); assertNotEquals(producerRecord, partitionMismatch); ProducerRecord<String, Integer> keyMisMatch = new ProducerRecord<>("test", 1, "key-1", 1); assertNotEquals(producerRecord, keyMisMatch); ProducerRecord<String, Integer> valueMisMatch = new ProducerRecord<>("test", 1, "key", 2); assertNotEquals(producerRecord, valueMisMatch); ProducerRecord<String, Integer> nullFieldsRecord = new ProducerRecord<>("topic", null, null, null, null, null); assertEquals(nullFieldsRecord, nullFieldsRecord); assertEquals(nullFieldsRecord.hashCode(), nullFieldsRecord.hashCode()); } @Test public void testInvalidRecords() { try { new ProducerRecord<>(null, 0, "key", 1); fail("Expected IllegalArgumentException to be raised because topic is null"); } catch (IllegalArgumentException e) { //expected } try { new ProducerRecord<>("test", 0, -1L, "key", 1); fail("Expected IllegalArgumentException to be raised because of negative timestamp"); } catch (IllegalArgumentException e) { //expected } try { new ProducerRecord<>("test", -1, "key", 1); fail("Expected IllegalArgumentException to be raised because of negative partition"); } catch (IllegalArgumentException e) { //expected } } }
ProducerRecordTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/netty/CreditBasedPartitionRequestClientHandlerTest.java
{ "start": 4960, "end": 44340 }
class ____ { private static Stream<Arguments> bufferDescriptors() { return Stream.of( Arguments.of(false, 1), // Scenario with a regular Buffer Arguments.of(true, 1), // FullyFilledBuffer with 1 partial buffer Arguments.of(true, 3) // FullyFilledBuffer with 3 partial buffers ); } private static Stream<Arguments> bufferDescriptorsWithCompression() { return Stream.of( Arguments.of(false, 1, "LZ4"), Arguments.of(false, 1, "LZO"), Arguments.of(false, 1, "ZSTD"), Arguments.of(true, 1, "LZ4"), Arguments.of(true, 1, "LZO"), Arguments.of(true, 1, "ZSTD"), Arguments.of(true, 3, "LZ4"), Arguments.of(true, 3, "LZO"), Arguments.of(true, 3, "ZSTD")); } /** * Tests a fix for FLINK-1627. * * <p>FLINK-1627 discovered a race condition, which could lead to an infinite loop when a * receiver was cancelled during a certain time of decoding a message. The test reproduces the * input, which lead to the infinite loop: when the handler gets a reference to the buffer * provider of the receiving input channel, but the respective input channel is released (and * the corresponding buffer provider destroyed), the handler did not notice this. * * @see <a href="https://issues.apache.org/jira/browse/FLINK-1627">FLINK-1627</a> */ @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") @Timeout(60) @SuppressWarnings("unchecked") void testReleaseInputChannelDuringDecode(boolean isFullyFilled, int numOfPartialBuffers) throws Exception { // Mocks an input channel in a state as it was released during a decode. final BufferProvider bufferProvider = mock(BufferProvider.class); when(bufferProvider.requestBuffer()).thenReturn(null); when(bufferProvider.isDestroyed()).thenReturn(true); when(bufferProvider.addBufferListener(any(BufferListener.class))).thenReturn(false); final RemoteInputChannel inputChannel = mock(RemoteInputChannel.class); when(inputChannel.getInputChannelId()).thenReturn(new InputChannelID()); when(inputChannel.getBufferProvider()).thenReturn(bufferProvider); final CreditBasedPartitionRequestClientHandler client = new CreditBasedPartitionRequestClientHandler(); client.addInputChannel(inputChannel); final BufferResponse receivedBuffer = createBufferResponse( createBuffer( isFullyFilled, numOfPartialBuffers, TestBufferFactory.BUFFER_SIZE), 0, inputChannel.getInputChannelId(), 2, new NetworkBufferAllocator(client)); client.channelRead(mock(ChannelHandlerContext.class), receivedBuffer); } /** * Tests a fix for FLINK-1761. * * <p>FLINK-1761 discovered an IndexOutOfBoundsException, when receiving buffers of size 0. */ @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") void testReceiveEmptyBuffer(boolean isFullyFilled, int numOfPartialBuffers) throws Exception { // Minimal mock of a remote input channel final BufferProvider bufferProvider = mock(BufferProvider.class); when(bufferProvider.requestBuffer()).thenReturn(TestBufferFactory.createBuffer(0)); final RemoteInputChannel inputChannel = mock(RemoteInputChannel.class); when(inputChannel.getInputChannelId()).thenReturn(new InputChannelID()); when(inputChannel.getBufferProvider()).thenReturn(bufferProvider); final CreditBasedPartitionRequestClientHandler client = new CreditBasedPartitionRequestClientHandler(); client.addInputChannel(inputChannel); final int backlog = 2; final BufferResponse receivedBuffer = createBufferResponse( createBuffer(isFullyFilled, numOfPartialBuffers, 0), 0, inputChannel.getInputChannelId(), backlog, new NetworkBufferAllocator(client)); // Read the empty buffer client.channelRead(mock(ChannelHandlerContext.class), receivedBuffer); // This should not throw an exception verify(inputChannel, never()).onError(any(Throwable.class)); verify(inputChannel, times(1)).onEmptyBuffer(0, backlog); } /** * Verifies that {@link RemoteInputChannel#onBuffer(Buffer, int, int, int)} is called when a * {@link BufferResponse} is received. */ @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") void testReceiveBuffer(boolean isFullyFilled, int numOfPartialBuffers) throws Exception { final NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, 32 * numOfPartialBuffers); final SingleInputGate inputGate = createSingleInputGate(1, networkBufferPool); final RemoteInputChannel inputChannel = InputChannelBuilder.newBuilder().buildRemoteChannel(inputGate); try { inputGate.setInputChannels(inputChannel); final BufferPool bufferPool = networkBufferPool.createBufferPool(8, 8); inputGate.setBufferPool(bufferPool); inputGate.setupChannels(); final CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); handler.addInputChannel(inputChannel); final int backlog = 2; final BufferResponse bufferResponse = createBufferResponse( createBuffer(isFullyFilled, numOfPartialBuffers, 32), 0, inputChannel.getInputChannelId(), backlog, new NetworkBufferAllocator(handler)); handler.channelRead(mock(ChannelHandlerContext.class), bufferResponse); assertThat(inputChannel.getNumberOfQueuedBuffers()).isEqualTo(numOfPartialBuffers); assertThat(inputChannel.getSenderBacklog()).isEqualTo(2); } finally { releaseResource(inputGate, networkBufferPool); } } /** * Verifies that {@link BufferResponse} of compressed {@link Buffer} can be handled correctly. */ @ParameterizedTest( name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}, compressionCodec={2}") @MethodSource("bufferDescriptorsWithCompression") void testReceiveCompressedBuffer( final boolean isFullyFilled, final int numOfPartialBuffers, final String compressionCodec) throws Exception { int bufferSize = 1024; BufferCompressor compressor = new BufferCompressor(bufferSize, CompressionCodec.valueOf(compressionCodec)); BufferDecompressor decompressor = new BufferDecompressor(bufferSize, CompressionCodec.valueOf(compressionCodec)); NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, bufferSize); SingleInputGate inputGate = new SingleInputGateBuilder() .setBufferDecompressor(decompressor) .setSegmentProvider(networkBufferPool) .build(); RemoteInputChannel inputChannel = createRemoteInputChannel(inputGate, null); inputGate.setInputChannels(inputChannel); try { BufferPool bufferPool = networkBufferPool.createBufferPool(8, 8); inputGate.setBufferPool(bufferPool); inputGate.setupChannels(); CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); handler.addInputChannel(inputChannel); BufferResponse bufferResponse = createBufferResponse( compressBuffer( compressor, createBuffer(isFullyFilled, numOfPartialBuffers, bufferSize)), 0, inputChannel.getInputChannelId(), 2, new NetworkBufferAllocator(handler)); assertThat(bufferResponse.isCompressed).isTrue(); handler.channelRead(null, bufferResponse); Buffer receivedBuffer = inputChannel.getNextReceivedBuffer(); assertThat(receivedBuffer).isNotNull(); assertThat(receivedBuffer.isCompressed()).isTrue(); receivedBuffer.recycleBuffer(); } finally { releaseResource(inputGate, networkBufferPool); } } /** Verifies that {@link NettyMessage.BacklogAnnouncement} can be handled correctly. */ @Test void testReceiveBacklogAnnouncement() throws Exception { int bufferSize = 1024; int numBuffers = 10; NetworkBufferPool networkBufferPool = new NetworkBufferPool(numBuffers, bufferSize); SingleInputGate inputGate = new SingleInputGateBuilder().setSegmentProvider(networkBufferPool).build(); RemoteInputChannel inputChannel = createRemoteInputChannel(inputGate, null); inputGate.setInputChannels(inputChannel); try { BufferPool bufferPool = networkBufferPool.createBufferPool(8, 8); inputGate.setBufferPool(bufferPool); inputGate.setupChannels(); CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); handler.addInputChannel(inputChannel); assertThat(inputChannel.getNumberOfAvailableBuffers()).isEqualTo(2); assertThat(inputChannel.unsynchronizedGetFloatingBuffersAvailable()).isZero(); int backlog = 5; NettyMessage.BacklogAnnouncement announcement = new NettyMessage.BacklogAnnouncement(backlog, inputChannel.getInputChannelId()); handler.channelRead(null, announcement); assertThat(inputChannel.getNumberOfAvailableBuffers()).isEqualTo(7); assertThat(inputChannel.getNumberOfRequiredBuffers()).isEqualTo(7); assertThat(inputChannel.getSenderBacklog()).isEqualTo(backlog); assertThat(inputChannel.unsynchronizedGetFloatingBuffersAvailable()).isEqualTo(5); backlog = 12; announcement = new NettyMessage.BacklogAnnouncement(backlog, inputChannel.getInputChannelId()); handler.channelRead(null, announcement); assertThat(inputChannel.getNumberOfAvailableBuffers()).isEqualTo(10); assertThat(inputChannel.getNumberOfRequiredBuffers()).isEqualTo(14); assertThat(inputChannel.getSenderBacklog()).isEqualTo(backlog); assertThat(inputChannel.unsynchronizedGetFloatingBuffersAvailable()).isEqualTo(8); } finally { releaseResource(inputGate, networkBufferPool); } } /** * Verifies that {@link RemoteInputChannel#onError(Throwable)} is called when a {@link * BufferResponse} is received but no available buffer in input channel. */ @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") void testThrowExceptionForNoAvailableBuffer(boolean isFullyFilled, int numOfPartialBuffers) throws Exception { final SingleInputGate inputGate = createSingleInputGate(1); final RemoteInputChannel inputChannel = spy(InputChannelBuilder.newBuilder().buildRemoteChannel(inputGate)); final CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); handler.addInputChannel(inputChannel); assertThat(inputChannel.getNumberOfAvailableBuffers()) .as("There should be no buffers available in the channel.") .isZero(); final BufferResponse bufferResponse = createBufferResponse( createBuffer( isFullyFilled, numOfPartialBuffers, TestBufferFactory.BUFFER_SIZE), 0, inputChannel.getInputChannelId(), 2, new NetworkBufferAllocator(handler)); assertThat(bufferResponse.getBuffer()).isNull(); handler.channelRead(mock(ChannelHandlerContext.class), bufferResponse); verify(inputChannel, times(1)).onError(any(IllegalStateException.class)); } /** * Verifies that {@link RemoteInputChannel#onFailedPartitionRequest()} is called when a {@link * PartitionNotFoundException} is received. */ @Test void testReceivePartitionNotFoundException() throws Exception { // Minimal mock of a remote input channel final BufferProvider bufferProvider = mock(BufferProvider.class); when(bufferProvider.requestBuffer()).thenReturn(TestBufferFactory.createBuffer(0)); final RemoteInputChannel inputChannel = mock(RemoteInputChannel.class); when(inputChannel.getInputChannelId()).thenReturn(new InputChannelID()); when(inputChannel.getBufferProvider()).thenReturn(bufferProvider); final ErrorResponse partitionNotFound = new ErrorResponse( new PartitionNotFoundException(new ResultPartitionID()), inputChannel.getInputChannelId()); final CreditBasedPartitionRequestClientHandler client = new CreditBasedPartitionRequestClientHandler(); client.addInputChannel(inputChannel); // Mock channel context ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); when(ctx.channel()).thenReturn(mock(Channel.class)); client.channelActive(ctx); client.channelRead(ctx, partitionNotFound); verify(inputChannel, times(1)).onFailedPartitionRequest(); } @Test void testCancelBeforeActive() throws Exception { final RemoteInputChannel inputChannel = mock(RemoteInputChannel.class); when(inputChannel.getInputChannelId()).thenReturn(new InputChannelID()); final CreditBasedPartitionRequestClientHandler client = new CreditBasedPartitionRequestClientHandler(); client.addInputChannel(inputChannel); // Don't throw NPE client.cancelRequestFor(null); // Don't throw NPE, because channel is not active yet client.cancelRequestFor(inputChannel.getInputChannelId()); } /** * Verifies that {@link RemoteInputChannel} is enqueued in the pipeline for notifying credits, * and verifies the behaviour of credit notification by triggering channel's writability * changed. */ @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") void testNotifyCreditAvailable(boolean isFullyFilled, int numOfPartialBuffers) throws Exception { final CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); final NetworkBufferAllocator allocator = new NetworkBufferAllocator(handler); final EmbeddedChannel channel = new EmbeddedChannel(handler); final PartitionRequestClient client = new NettyPartitionRequestClient( channel, handler, mock(ConnectionID.class), mock(PartitionRequestClientFactory.class)); final NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, 32 * numOfPartialBuffers); final SingleInputGate inputGate = createSingleInputGate(2, networkBufferPool); final RemoteInputChannel[] inputChannels = new RemoteInputChannel[2]; inputChannels[0] = createRemoteInputChannel(inputGate, client); inputChannels[1] = createRemoteInputChannel(inputGate, client); try { inputGate.setInputChannels(inputChannels); final BufferPool bufferPool = networkBufferPool.createBufferPool(6, 6); inputGate.setBufferPool(bufferPool); inputGate.setupChannels(); inputChannels[0].requestSubpartitions(); inputChannels[1].requestSubpartitions(); // The two input channels should send partition requests assertThat(channel.isWritable()).isTrue(); Object readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound).isInstanceOf(PartitionRequest.class); assertThat(inputChannels[0].getInputChannelId()) .isEqualTo(((PartitionRequest) readFromOutbound).receiverId); assertThat(((PartitionRequest) readFromOutbound).credit).isEqualTo(2); readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound).isInstanceOf(PartitionRequest.class); assertThat(inputChannels[1].getInputChannelId()) .isEqualTo(((PartitionRequest) readFromOutbound).receiverId); assertThat(((PartitionRequest) readFromOutbound).credit).isEqualTo(2); // The buffer response will take one available buffer from input channel, and it will // trigger // requesting (backlog + numExclusiveBuffers - numAvailableBuffers) floating buffers final BufferResponse bufferResponse1 = createBufferResponse( createBuffer(isFullyFilled, numOfPartialBuffers, 32), 0, inputChannels[0].getInputChannelId(), 1, allocator); final BufferResponse bufferResponse2 = createBufferResponse( createBuffer(isFullyFilled, numOfPartialBuffers, 32), 0, inputChannels[1].getInputChannelId(), 1, allocator); handler.channelRead(mock(ChannelHandlerContext.class), bufferResponse1); handler.channelRead(mock(ChannelHandlerContext.class), bufferResponse2); assertThat(inputChannels[0].getUnannouncedCredit()).isEqualTo(2); assertThat(inputChannels[1].getUnannouncedCredit()).isEqualTo(2); channel.runPendingTasks(); // The two input channels should notify credits availability via the writable channel readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound).isInstanceOf(AddCredit.class); assertThat(inputChannels[0].getInputChannelId()) .isEqualTo(((AddCredit) readFromOutbound).receiverId); assertThat(((AddCredit) readFromOutbound).credit).isEqualTo(2); readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound).isInstanceOf(AddCredit.class); assertThat(inputChannels[1].getInputChannelId()) .isEqualTo(((AddCredit) readFromOutbound).receiverId); assertThat(((AddCredit) readFromOutbound).credit).isEqualTo(2); assertThat((Object) channel.readOutbound()).isNull(); ByteBuf channelBlockingBuffer = blockChannel(channel); // Trigger notify credits availability via buffer response on the condition of an // un-writable channel final BufferResponse bufferResponse3 = createBufferResponse( createBuffer(isFullyFilled, numOfPartialBuffers, 32), numOfPartialBuffers, inputChannels[0].getInputChannelId(), 1, allocator); handler.channelRead(mock(ChannelHandlerContext.class), bufferResponse3); assertThat(inputChannels[0].getUnannouncedCredit()).isOne(); assertThat(inputChannels[1].getUnannouncedCredit()).isZero(); channel.runPendingTasks(); // The input channel will not notify credits via un-writable channel assertThat(channel.isWritable()).isFalse(); assertThat((Object) channel.readOutbound()).isNull(); // Flush the buffer to make the channel writable again channel.flush(); assertThat(channelBlockingBuffer).isSameAs(channel.readOutbound()); // The input channel should notify credits via channel's writability changed event assertThat(channel.isWritable()).isTrue(); readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound).isInstanceOf(AddCredit.class); assertThat(((AddCredit) readFromOutbound).credit).isOne(); assertThat(inputChannels[0].getUnannouncedCredit()).isZero(); assertThat(inputChannels[1].getUnannouncedCredit()).isZero(); // no more messages assertThat((Object) channel.readOutbound()).isNull(); } finally { releaseResource(inputGate, networkBufferPool); channel.close(); } } /** * Verifies that {@link RemoteInputChannel} is enqueued in the pipeline, but {@link AddCredit} * message is not sent actually when this input channel is released. */ @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") void testNotifyCreditAvailableAfterReleased(boolean isFullyFilled, int numOfPartialBuffers) throws Exception { final CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); final EmbeddedChannel channel = new EmbeddedChannel(handler); final PartitionRequestClient client = new NettyPartitionRequestClient( channel, handler, mock(ConnectionID.class), mock(PartitionRequestClientFactory.class)); final NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, 32 * numOfPartialBuffers); final SingleInputGate inputGate = createSingleInputGate(1, networkBufferPool); final RemoteInputChannel inputChannel = createRemoteInputChannel(inputGate, client); try { inputGate.setInputChannels(inputChannel); final BufferPool bufferPool = networkBufferPool.createBufferPool(6, 6); inputGate.setBufferPool(bufferPool); inputGate.setupChannels(); inputChannel.requestSubpartitions(); // This should send the partition request Object readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound).isInstanceOf(PartitionRequest.class); assertThat(((PartitionRequest) readFromOutbound).credit).isEqualTo(2); // Trigger request floating buffers via buffer response to notify credits available final BufferResponse bufferResponse = createBufferResponse( createBuffer(isFullyFilled, numOfPartialBuffers, 32), 0, inputChannel.getInputChannelId(), 1, new NetworkBufferAllocator(handler)); handler.channelRead(mock(ChannelHandlerContext.class), bufferResponse); assertThat(inputChannel.getUnannouncedCredit()).isEqualTo(2); // Release the input channel inputGate.close(); // it should send a close request after releasing the input channel, // but will not notify credits for a released input channel. readFromOutbound = channel.readOutbound(); assertThat(readFromOutbound).isInstanceOf(CloseRequest.class); channel.runPendingTasks(); assertThat((Object) channel.readOutbound()).isNull(); } finally { releaseResource(inputGate, networkBufferPool); channel.close(); } } @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") void testReadBufferResponseBeforeReleasingChannel( boolean isFullyFilled, int numOfPartialBuffers) throws Exception { testReadBufferResponseWithReleasingOrRemovingChannel( isFullyFilled, false, true, numOfPartialBuffers); } @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") void testReadBufferResponseBeforeRemovingChannel(boolean isFullyFilled, int numOfPartialBuffers) throws Exception { testReadBufferResponseWithReleasingOrRemovingChannel( isFullyFilled, true, true, numOfPartialBuffers); } @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") void testReadBufferResponseAfterReleasingChannel(boolean isFullyFilled, int numOfPartialBuffers) throws Exception { testReadBufferResponseWithReleasingOrRemovingChannel( isFullyFilled, false, false, numOfPartialBuffers); } @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") void testReadBufferResponseAfterRemovingChannel(boolean isFullyFilled, int numOfPartialBuffers) throws Exception { testReadBufferResponseWithReleasingOrRemovingChannel( isFullyFilled, true, false, numOfPartialBuffers); } @ParameterizedTest(name = "{index} => isFullyFilled={0}, numOfPartialBuffers={1}") @MethodSource("bufferDescriptors") void testDoNotFailHandlerOnSingleChannelFailure(boolean isFullyFilled, int numOfPartialBuffers) throws Exception { // Setup final int bufferSize = 1024; final String expectedMessage = "test exception on buffer"; final NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, bufferSize * numOfPartialBuffers); final SingleInputGate inputGate = createSingleInputGate(1, networkBufferPool); final RemoteInputChannel inputChannel = new TestRemoteInputChannelForError(inputGate, expectedMessage); final CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); try { inputGate.setInputChannels(inputChannel); inputGate.setup(); inputGate.requestPartitions(); handler.addInputChannel(inputChannel); final BufferResponse bufferResponse = createBufferResponse( createBuffer(isFullyFilled, numOfPartialBuffers, bufferSize), 0, inputChannel.getInputChannelId(), 1, new NetworkBufferAllocator(handler)); // It will trigger an expected exception from TestRemoteInputChannelForError#onBuffer handler.channelRead(null, bufferResponse); // The handler should not be tagged as error for above excepted exception handler.checkError(); // The input channel should be tagged as error and the respective exception is // thrown via #getNext assertThatThrownBy(inputGate::getNext) .isInstanceOf(IOException.class) .hasMessage(expectedMessage); } finally { // Cleanup releaseResource(inputGate, networkBufferPool); } } @Test void testExceptionWrap() { testExceptionWrap(LocalTransportException.class, new Exception()); testExceptionWrap(LocalTransportException.class, new Exception("some error")); testExceptionWrap( RemoteTransportException.class, new IOException("Connection reset by peer")); // Only when Epoll is available the following exception could be initiated normally // since it relies on the native strerror method. assumeThat(Epoll.isAvailable()).isTrue(); testExceptionWrap( RemoteTransportException.class, new Errors.NativeIoException("readAddress", Errors.ERRNO_ECONNRESET_NEGATIVE)); } private void testExceptionWrap( Class<? extends TransportException> expectedClass, Exception cause) { CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); handler.setConnectionId( new ConnectionID(ResourceID.generate(), new InetSocketAddress("localhost", 0), 0)); EmbeddedChannel embeddedChannel = new EmbeddedChannel( // A test handler to trigger the exception. new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { throw cause; } }, handler); embeddedChannel.writeInbound(1); assertThatThrownBy(() -> handler.checkError()) .isInstanceOf(expectedClass) .withFailMessage( String.format( "The handler should wrap the exception %s as %s, but it does not.", cause, expectedClass)); } @Test void testAnnounceBufferSize() throws Exception { final CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); final EmbeddedChannel channel = new EmbeddedChannel(handler); final PartitionRequestClient client = new NettyPartitionRequestClient( channel, handler, mock(ConnectionID.class), mock(PartitionRequestClientFactory.class)); final NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, 32); final SingleInputGate inputGate = createSingleInputGate(2, networkBufferPool); final RemoteInputChannel[] inputChannels = new RemoteInputChannel[2]; inputChannels[0] = createRemoteInputChannel(inputGate, client); inputChannels[1] = createRemoteInputChannel(inputGate, client); try { inputGate.setInputChannels(inputChannels); final BufferPool bufferPool = networkBufferPool.createBufferPool(6, 6); inputGate.setBufferPool(bufferPool); inputGate.setupChannels(); inputChannels[0].requestSubpartitions(); inputChannels[1].requestSubpartitions(); channel.readOutbound(); channel.readOutbound(); inputGate.announceBufferSize(333); channel.runPendingTasks(); NettyMessage.NewBufferSize readOutbound = channel.readOutbound(); assertThat(readOutbound).isInstanceOf(NettyMessage.NewBufferSize.class); assertThat(inputChannels[0].getInputChannelId()).isEqualTo(readOutbound.receiverId); assertThat(readOutbound.bufferSize).isEqualTo(333); readOutbound = channel.readOutbound(); assertThat(inputChannels[1].getInputChannelId()).isEqualTo(readOutbound.receiverId); assertThat(readOutbound.bufferSize).isEqualTo(333); } finally { releaseResource(inputGate, networkBufferPool); channel.close(); } } private void testReadBufferResponseWithReleasingOrRemovingChannel( boolean isFullyFilled, boolean isRemoved, boolean readBeforeReleasingOrRemoving, int numOfPartialBuffers) throws Exception { int bufferSize = 1024; NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, bufferSize * numOfPartialBuffers); SingleInputGate inputGate = createSingleInputGate(1, networkBufferPool); RemoteInputChannel inputChannel = new InputChannelBuilder().buildRemoteChannel(inputGate); inputGate.setInputChannels(inputChannel); inputGate.setup(); CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); EmbeddedChannel embeddedChannel = new EmbeddedChannel(handler); handler.addInputChannel(inputChannel); try { if (!readBeforeReleasingOrRemoving) { // Release the channel. inputGate.close(); if (isRemoved) { handler.removeInputChannel(inputChannel); } } BufferResponse bufferResponse = createBufferResponse( createBuffer(isFullyFilled, numOfPartialBuffers, bufferSize), 0, inputChannel.getInputChannelId(), 1, new NetworkBufferAllocator(handler)); if (readBeforeReleasingOrRemoving) { // Release the channel. inputGate.close(); if (isRemoved) { handler.removeInputChannel(inputChannel); } } handler.channelRead(null, bufferResponse); assertThat(inputChannel.getNumberOfQueuedBuffers()).isZero(); if (!readBeforeReleasingOrRemoving) { assertThat(bufferResponse.getBuffer()).isNull(); } else { assertThat(bufferResponse.getBuffer()).isNotNull(); assertThat(bufferResponse.getBuffer().isRecycled()).isTrue(); } embeddedChannel.runScheduledPendingTasks(); NettyMessage.CancelPartitionRequest cancelPartitionRequest = embeddedChannel.readOutbound(); assertThat(cancelPartitionRequest).isNotNull(); assertThat(inputChannel.getInputChannelId()) .isEqualTo(cancelPartitionRequest.receiverId); } finally { releaseResource(inputGate, networkBufferPool); embeddedChannel.close(); } } private static void releaseResource( SingleInputGate inputGate, NetworkBufferPool networkBufferPool) throws IOException { // Release all the buffer resources inputGate.close(); networkBufferPool.destroyAllBufferPools(); networkBufferPool.destroy(); } /** Returns a deserialized buffer message as it would be received during runtime. */ private static BufferResponse createBufferResponse( Buffer buffer, int sequenceNumber, InputChannelID receivingChannelId, int backlog, NetworkBufferAllocator allocator) throws IOException { // Check if the buffer is an instance of FullyFilledBuffer if (buffer instanceof FullyFilledBuffer) { FullyFilledBuffer fullyFilledBuffer = (FullyFilledBuffer) buffer; int partialBuffers = fullyFilledBuffer.getPartialBuffers().size(); BufferResponse resp = new BufferResponse( buffer, sequenceNumber, receivingChannelId, 0, partialBuffers, backlog); ByteBuf serialized = resp.write(UnpooledByteBufAllocator.DEFAULT); // Skip general header bytes serialized.readBytes(NettyMessage.FRAME_HEADER_LENGTH); // Deserialize the bytes to construct the BufferResponse. BufferResponse bufferResponse = BufferResponse.readFrom(serialized, allocator); // Add partial buffer sizes to the response for (Buffer partialBuffer : fullyFilledBuffer.getPartialBuffers()) { bufferResponse.getPartialBufferSizes().add(partialBuffer.getSize()); } return bufferResponse; } else { // Construct BufferResponse normally when there are no partial buffers BufferResponse resp = new BufferResponse(buffer, sequenceNumber, receivingChannelId, 0, 0, backlog); ByteBuf serialized = resp.write(UnpooledByteBufAllocator.DEFAULT); // Skip general header bytes serialized.readBytes(NettyMessage.FRAME_HEADER_LENGTH); // Deserialize the bytes to construct the BufferResponse. return BufferResponse.readFrom(serialized, allocator); } } private static Buffer createBuffer( boolean isFullyFilled, int numOfPartialBuffers, int bufferSize) { if (!isFullyFilled) { return TestBufferFactory.createBuffer(bufferSize); } else { return createFullyFilledBuffer(numOfPartialBuffers, bufferSize); } } private static FullyFilledBuffer createFullyFilledBuffer( int numOfPartialBuffers, int bufferSize) { FullyFilledBuffer buffer = new FullyFilledBuffer( Buffer.DataType.DATA_BUFFER, bufferSize * numOfPartialBuffers, false); for (int i = 0; i < numOfPartialBuffers; i++) { buffer.addPartialBuffer(TestBufferFactory.createBuffer(bufferSize)); } return buffer; } private static Buffer compressBuffer(BufferCompressor compressor, Buffer buffer) { if (buffer instanceof FullyFilledBuffer) { FullyFilledBuffer fullyFilledBuffer = (FullyFilledBuffer) buffer; FullyFilledBuffer newFullyFilledBuffer = new FullyFilledBuffer(buffer.getDataType(), buffer.getSize(), true); for (Buffer partialBuffer : fullyFilledBuffer.getPartialBuffers()) { newFullyFilledBuffer.addPartialBuffer( compressor.compressToOriginalBuffer(partialBuffer)); } return newFullyFilledBuffer; } else { return compressor.compressToOriginalBuffer(buffer); } } /** * The test remote input channel to throw expected exception while calling {@link * RemoteInputChannel#onBuffer(Buffer, int, int, int)}. */ private static
CreditBasedPartitionRequestClientHandlerTest
java
apache__flink
flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/PatternProcessFunctionBuilder.java
{ "start": 2443, "end": 3425 }
class ____<IN, OUT> { private final PatternFlatSelectFunction<IN, OUT> flatSelectFunction; FlatSelectBuilder(PatternFlatSelectFunction<IN, OUT> function) { this.flatSelectFunction = checkNotNull(function); } <TIMED_OUT> FlatTimeoutSelectBuilder<IN, OUT, TIMED_OUT> withTimeoutHandler( final OutputTag<TIMED_OUT> outputTag, final PatternFlatTimeoutFunction<IN, TIMED_OUT> timeoutHandler) { return new FlatTimeoutSelectBuilder<>(flatSelectFunction, timeoutHandler, outputTag); } PatternProcessFunction<IN, OUT> build() { return new PatternFlatSelectAdapter<>(flatSelectFunction); } } /** * Wraps {@link PatternFlatSelectFunction} and {@link PatternFlatTimeoutFunction} in a builder. * The builder will create a {@link PatternProcessFunction} adapter that handles timed out * partial matches as well. */ static
FlatSelectBuilder
java
FasterXML__jackson-core
src/main/java/tools/jackson/core/json/async/NonBlockingJsonParserBase.java
{ "start": 449, "end": 506 }
class ____ non-blocking JSON parsers. */ public abstract
for
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/convention/TestBeanForMultipleNestingLevelsIntegrationTests.java
{ "start": 2576, "end": 2833 }
class ____ { @Bean String field0() { return "replace me 0"; } @Bean String field1() { return "replace me 1"; } @Bean String field2() { return "replace me 2"; } @Bean String field3() { return "replace me 3"; } } }
Config
java
apache__flink
flink-python/src/main/java/org/apache/flink/python/metric/process/FlinkMetricContainer.java
{ "start": 2606, "end": 11059 }
class ____ { private static final ObjectMapper OBJECT_MAPPER = JacksonMapperFactory.createObjectMapper(); private static final String METRIC_KEY_SEPARATOR = GlobalConfiguration.loadConfiguration().get(MetricOptions.SCOPE_DELIMITER); private final MetricsContainerStepMap metricsContainers; private final MetricGroup baseMetricGroup; private final Map<String, Counter> flinkCounterCache; private final Map<String, Meter> flinkMeterCache; private final Map<String, FlinkDistributionGauge> flinkDistributionGaugeCache; private final Map<String, FlinkGauge> flinkGaugeCache; public FlinkMetricContainer(MetricGroup metricGroup) { this.baseMetricGroup = checkNotNull(metricGroup); this.flinkCounterCache = new HashMap<>(); this.flinkMeterCache = new HashMap<>(); this.flinkDistributionGaugeCache = new HashMap<>(); this.flinkGaugeCache = new HashMap<>(); this.metricsContainers = new MetricsContainerStepMap(); } private MetricsContainerImpl getMetricsContainer(String stepName) { return metricsContainers.getContainer(stepName); } /** * Update this container with metrics from the passed {@link MonitoringInfo}s, and send updates * along to Flink's internal metrics framework. */ public void updateMetrics(String stepName, List<MonitoringInfo> monitoringInfos) { getMetricsContainer(stepName).update(monitoringInfos); updateMetrics(stepName); } /** * Update Flink's internal metrics ({@link #flinkCounterCache}) with the latest metrics for a * given step. */ private void updateMetrics(String stepName) { MetricResults metricResults = asAttemptedOnlyMetricResults(metricsContainers); MetricQueryResults metricQueryResults = metricResults.queryMetrics(MetricsFilter.builder().addStep(stepName).build()); updateCounterOrMeter(metricQueryResults.getCounters()); updateDistributions(metricQueryResults.getDistributions()); updateGauge(metricQueryResults.getGauges()); } private boolean isUserMetric(MetricResult metricResult) { MetricName metricName = metricResult.getKey().metricName(); if (metricName instanceof MonitoringInfoMetricName) { String urn = ((MonitoringInfoMetricName) metricName).getUrn(); return urn.startsWith("beam:metric:user"); } return false; } private void updateCounterOrMeter(Iterable<MetricResult<Long>> counters) { for (MetricResult<Long> metricResult : counters) { if (!isUserMetric(metricResult)) { continue; } // get identifier String flinkMetricIdentifier = getFlinkMetricIdentifierString(metricResult.getKey()); // get metric type ArrayList<String> scopeComponents = getNameSpaceArray(metricResult.getKey()); if ((scopeComponents.size() % 2) != 0) { Meter meter = flinkMeterCache.get(flinkMetricIdentifier); if (null == meter) { int timeSpanInSeconds = Integer.parseInt(scopeComponents.get(scopeComponents.size() - 1)); MetricGroup metricGroup = registerMetricGroup(metricResult.getKey(), baseMetricGroup); meter = metricGroup.meter( metricResult.getKey().metricName().getName(), new MeterView(timeSpanInSeconds)); flinkMeterCache.put(flinkMetricIdentifier, meter); } Long update = metricResult.getAttempted(); meter.markEvent(update - meter.getCount()); } else { Counter counter = flinkCounterCache.get(flinkMetricIdentifier); if (null == counter) { MetricGroup metricGroup = registerMetricGroup(metricResult.getKey(), baseMetricGroup); counter = metricGroup.counter(metricResult.getKey().metricName().getName()); flinkCounterCache.put(flinkMetricIdentifier, counter); } Long update = metricResult.getAttempted(); counter.inc(update - counter.getCount()); } } } private void updateDistributions(Iterable<MetricResult<DistributionResult>> distributions) { for (MetricResult<DistributionResult> metricResult : distributions) { if (!isUserMetric(metricResult)) { continue; } // get identifier String flinkMetricIdentifier = getFlinkMetricIdentifierString(metricResult.getKey()); DistributionResult update = metricResult.getAttempted(); // update flink metric FlinkDistributionGauge gauge = flinkDistributionGaugeCache.get(flinkMetricIdentifier); if (gauge == null) { MetricGroup metricGroup = registerMetricGroup(metricResult.getKey(), baseMetricGroup); gauge = metricGroup.gauge( metricResult.getKey().metricName().getName(), new FlinkDistributionGauge(update)); flinkDistributionGaugeCache.put(flinkMetricIdentifier, gauge); } else { gauge.update(update); } } } private void updateGauge(Iterable<MetricResult<GaugeResult>> gauges) { for (MetricResult<GaugeResult> metricResult : gauges) { if (!isUserMetric(metricResult)) { continue; } // get identifier String flinkMetricIdentifier = getFlinkMetricIdentifierString(metricResult.getKey()); GaugeResult update = metricResult.getAttempted(); // update flink metric FlinkGauge gauge = flinkGaugeCache.get(flinkMetricIdentifier); if (gauge == null) { MetricGroup metricGroup = registerMetricGroup(metricResult.getKey(), baseMetricGroup); gauge = metricGroup.gauge( metricResult.getKey().metricName().getName(), new FlinkGauge(update)); flinkGaugeCache.put(flinkMetricIdentifier, gauge); } else { gauge.update(update); } } } @VisibleForTesting static ArrayList getNameSpaceArray(MetricKey metricKey) { MetricName metricName = metricKey.metricName(); try { return OBJECT_MAPPER.readValue(metricName.getNamespace(), ArrayList.class); } catch (JsonProcessingException e) { throw new RuntimeException( String.format("Parse namespace[%s] error. ", metricName.getNamespace()), e); } } @VisibleForTesting static String getFlinkMetricIdentifierString(MetricKey metricKey) { MetricName metricName = metricKey.metricName(); ArrayList<String> scopeComponents = getNameSpaceArray(metricKey); List<String> results = scopeComponents.subList(0, scopeComponents.size() / 2); results.add(metricName.getName()); return String.join(METRIC_KEY_SEPARATOR, results); } @VisibleForTesting static MetricGroup registerMetricGroup(MetricKey metricKey, MetricGroup metricGroup) { ArrayList<String> scopeComponents = getNameSpaceArray(metricKey); int size = scopeComponents.size(); List<String> metricGroupNames = scopeComponents.subList(0, size / 2); List<String> metricGroupTypes = scopeComponents.subList(size / 2, size); for (int i = 0; i < metricGroupNames.size(); ++i) { if (metricGroupTypes.get(i).equals("MetricGroupType.generic")) { metricGroup = metricGroup.addGroup(metricGroupNames.get(i)); } else if (metricGroupTypes.get(i).equals("MetricGroupType.key")) { metricGroup = metricGroup.addGroup(metricGroupNames.get(i), metricGroupNames.get(++i)); } } return metricGroup; } /** Flink {@link Gauge} for {@link DistributionResult}. */ public static
FlinkMetricContainer
java
spring-projects__spring-boot
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java
{ "start": 1024, "end": 2746 }
class ____ { public static final byte[] BYTES = "ABC".getBytes(); @Test @SuppressWarnings("NullAway") // Test null check void kindMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(null, null)) .withMessageContaining("'kind' must not be null"); } @Test @SuppressWarnings("NullAway") // Test null check void addedContentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.ADDED, null)) .withMessageContaining("'contents' must not be null"); } @Test @SuppressWarnings("NullAway") // Test null check void modifiedContentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.MODIFIED, null)) .withMessageContaining("'contents' must not be null"); } @Test @SuppressWarnings("NullAway") // Test null check void deletedContentsMustBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.DELETED, new byte[10])) .withMessageContaining("'contents' must be null"); } @Test void added() { ClassLoaderFile file = new ClassLoaderFile(Kind.ADDED, BYTES); assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.ADDED); assertThat(file.getContents()).isEqualTo(BYTES); } @Test void modified() { ClassLoaderFile file = new ClassLoaderFile(Kind.MODIFIED, BYTES); assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.MODIFIED); assertThat(file.getContents()).isEqualTo(BYTES); } @Test void deleted() { ClassLoaderFile file = new ClassLoaderFile(Kind.DELETED, null); assertThat(file.getKind()).isEqualTo(ClassLoaderFile.Kind.DELETED); assertThat(file.getContents()).isNull(); } }
ClassLoaderFileTests
java
reactor__reactor-core
benchmarks/src/main/java/reactor/core/scrabble/ShakespearePlaysScrabbleOpt.java
{ "start": 990, "end": 7140 }
class ____ extends ShakespearePlaysScrabble { public static void main(String[] args) throws Exception { ShakespearePlaysScrabbleOpt s = new ShakespearePlaysScrabbleOpt(); s.init(); System.out.println(s.measureThroughput()); } @SuppressWarnings("unused") @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Warmup(iterations = 5, time = 1) @Measurement(iterations = 5, time = 1) @Fork(1) public List<Entry<Integer, List<String>>> measureThroughput() throws InterruptedException { // to compute the score of a given word Function<Integer, Integer> scoreOfALetter = letter -> letterScores[letter - 'a']; // score of the same letters in a word Function<Entry<Integer, MutableLong>, Integer> letterScore = entry -> letterScores[entry.getKey() - 'a'] * Integer.min((int) entry.getValue() .get(), scrabbleAvailableLetters[entry.getKey() - 'a']); Function<String, Flux<Integer>> toIntegerFlux = ShakespearePlaysScrabbleOpt::chars; // Histogram of the letters in a given word Function<String, Mono<Map<Integer, MutableLong>>> histoOfLetters = word -> toIntegerFlux.apply(word) .collect(HashMap::new, (Map<Integer, MutableLong> map, Integer value) -> { MutableLong newValue = map.get(value); if (newValue == null) { newValue = new MutableLong(); map.put(value, newValue); } newValue.incAndSet(); } ); // number of blanks for a given letter Function<Entry<Integer, MutableLong>, Long> blank = entry -> Long.max(0L, entry.getValue() .get() - scrabbleAvailableLetters[entry.getKey() - 'a']); // number of blanks for a given word Function<String, Mono<Long>> nBlanks = word -> MathFlux.sumLong(histoOfLetters.apply(word) .flatMapIterable(Map::entrySet) .map(blank)); // can a word be written with 2 blanks? Function<String, Mono<Boolean>> checkBlanks = word -> nBlanks.apply(word) .map(l -> l <= 2L); // score taking blanks into account letterScore1 Function<String, Mono<Integer>> score2 = word -> MathFlux.sumInt(histoOfLetters.apply(word) .flatMapIterable(Map::entrySet) .map(letterScore)); // Placing the word on the board // Building the Fluxs of first and last letters Function<String, Flux<Integer>> first3 = word -> chars(word).take(3); Function<String, Flux<Integer>> last3 = word -> chars(word).skip(3); // Flux to be maxed Function<String, Flux<Integer>> toBeMaxed = word -> Flux.concat(first3.apply(word), last3.apply(word)); // Bonus for double letter Function<String, Mono<Integer>> bonusForDoubleLetter = word -> MathFlux.max(toBeMaxed.apply(word) .map(scoreOfALetter)); // score of the word put on the board Function<String, Mono<Integer>> score3 = word -> MathFlux.sumInt(score2.apply(word) .concatWith(bonusForDoubleLetter.apply( word))) .map(v -> 2 * v + (word.length() == 7 ? 50 : 0)); Function<Function<String, Mono<Integer>>, Mono<TreeMap<Integer, List<String>>>> buildHistoOnScore = score -> Flux.fromIterable(shakespeareWords) .filter(word -> scrabbleWords.contains(word) && checkBlanks.apply(word) .block()) .collect(() -> new TreeMap<>(Comparator.reverseOrder()), (TreeMap<Integer, List<String>> map, String word) -> { Integer key = score.apply(word) .block(); List<String> list = map.get(key); if (list == null) { list = new ArrayList<>(); map.put(key, list); } list.add(word); }); // best key / value pairs return buildHistoOnScore.apply(score3) .flatMapIterable(Map::entrySet) .take(3) .collectList() .block(); } static Flux<Integer> chars(String word) { //return Flux.range(0, word.length()).map(i -> (int)word.charAt(i)); return new FluxCharSequence(word); } }
ShakespearePlaysScrabbleOpt
java
apache__flink
flink-table/flink-sql-gateway-api/src/main/java/org/apache/flink/table/gateway/api/utils/SqlGatewayException.java
{ "start": 990, "end": 1345 }
class ____ extends RuntimeException { private static final long serialVersionUID = 1L; public SqlGatewayException(String message) { super(message); } public SqlGatewayException(String message, Throwable e) { super(message, e); } public SqlGatewayException(Throwable e) { super(e); } }
SqlGatewayException
java
apache__camel
components/camel-milo/src/main/java/org/apache/camel/component/milo/client/MonitorFilterType.java
{ "start": 859, "end": 908 }
enum ____ { dataChangeFilter; }
MonitorFilterType