Java Code Examples for com.google.common.collect.RangeSet#asRanges()

The following examples show how to use com.google.common.collect.RangeSet#asRanges() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DateRangeRules.java    From Bats with Apache License 2.0 6 votes vote down vote up
private boolean canRewriteExtract(RexNode operand) {
    // We rely on timeUnits being sorted (so YEAR comes before MONTH
    // before HOUR) and unique. If we have seen a predicate on YEAR,
    // operandRanges will not be empty. This checks whether we can rewrite
    // the "extract" condition. For example, in the condition
    //
    // extract(MONTH from time) = someValue
    // OR extract(YEAR from time) = someValue
    //
    // we cannot rewrite extract on MONTH.
    if (timeUnit == TimeUnitRange.YEAR) {
        return true;
    }
    final RangeSet<Calendar> calendarRangeSet = operandRanges.get(operand);
    if (calendarRangeSet == null || calendarRangeSet.isEmpty()) {
        return false;
    }
    for (Range<Calendar> range : calendarRangeSet.asRanges()) {
        // Cannot reWrite if range does not have an upper or lower bound
        if (!range.hasUpperBound() || !range.hasLowerBound()) {
            return false;
        }
    }
    return true;
}
 
Example 2
Source File: DateRangeRules.java    From Quicksql with MIT License 6 votes vote down vote up
private boolean canRewriteExtract(RexNode operand) {
  // We rely on timeUnits being sorted (so YEAR comes before MONTH
  // before HOUR) and unique. If we have seen a predicate on YEAR,
  // operandRanges will not be empty. This checks whether we can rewrite
  // the "extract" condition. For example, in the condition
  //
  //   extract(MONTH from time) = someValue
  //   OR extract(YEAR from time) = someValue
  //
  // we cannot rewrite extract on MONTH.
  if (timeUnit == TimeUnitRange.YEAR) {
    return true;
  }
  final RangeSet<Calendar> calendarRangeSet = operandRanges.get(operand);
  if (calendarRangeSet == null || calendarRangeSet.isEmpty()) {
    return false;
  }
  for (Range<Calendar> range : calendarRangeSet.asRanges()) {
    // Cannot reWrite if range does not have an upper or lower bound
    if (!range.hasUpperBound() || !range.hasLowerBound()) {
      return false;
    }
  }
  return true;
}
 
Example 3
Source File: QuoteFilter.java    From tac-kbp-eal with MIT License 6 votes vote down vote up
private QuoteFilter(Map<Symbol, ImmutableRangeSet<Integer>> docIdToBannedRegions) {
  this.docIdToBannedRegions = ImmutableMap.copyOf(docIdToBannedRegions);
  for (RangeSet<Integer> rs : docIdToBannedRegions.values()) {
    for (final Range<Integer> r : rs.asRanges()) {
      checkArgument(r.hasLowerBound());
      checkArgument(r.hasUpperBound());
      checkArgument(r.lowerEndpoint() >= 0);
    }
  }
  // these ensure we can serialize safely
  for (Symbol sym : docIdToBannedRegions.keySet()) {
    final String s = sym.toString();
    checkArgument(!s.isEmpty(), "Document IDs may not be empty");
    checkArgument(!CharMatcher.WHITESPACE.matchesAnyOf(s),
        "Document IDs may not contain whitespace: %s", s);
  }
}
 
Example 4
Source File: DateRangeRules.java    From calcite with Apache License 2.0 6 votes vote down vote up
private boolean canRewriteExtract(RexNode operand) {
  // We rely on timeUnits being sorted (so YEAR comes before MONTH
  // before HOUR) and unique. If we have seen a predicate on YEAR,
  // operandRanges will not be empty. This checks whether we can rewrite
  // the "extract" condition. For example, in the condition
  //
  //   extract(MONTH from time) = someValue
  //   OR extract(YEAR from time) = someValue
  //
  // we cannot rewrite extract on MONTH.
  if (timeUnit == TimeUnitRange.YEAR) {
    return true;
  }
  final RangeSet<Calendar> calendarRangeSet = operandRanges.get(operand);
  if (calendarRangeSet == null || calendarRangeSet.isEmpty()) {
    return false;
  }
  for (Range<Calendar> range : calendarRangeSet.asRanges()) {
    // Cannot reWrite if range does not have an upper or lower bound
    if (!range.hasUpperBound() || !range.hasLowerBound()) {
      return false;
    }
  }
  return true;
}
 
Example 5
Source File: AbstractConsoleEventBusListener.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Get the summed elapsed time from all matched event pairs. Does not consider unmatched event
 * pairs. Pairs are determined by their {@link com.facebook.buck.event.EventKey}.
 *
 * @param eventIntervals a set of paired events (incomplete events are okay).
 * @return the sum of all times between matched event pairs.
 */
protected static long getTotalCompletedTimeFromEventIntervals(
    Collection<EventInterval> eventIntervals) {
  long totalTime = 0L;
  // Flatten the event groupings into a timeline, so that we don't over count parallel work.
  RangeSet<Long> timeline = TreeRangeSet.create();
  for (EventInterval pair : eventIntervals) {
    if (pair.isComplete() && pair.getElapsedTimeMs() > 0) {
      timeline.add(Range.open(pair.getStartTime(), pair.getEndTime()));
    }
  }
  for (Range<Long> range : timeline.asRanges()) {
    totalTime += range.upperEndpoint() - range.lowerEndpoint();
  }
  return totalTime;
}
 
Example 6
Source File: AccessControlListApiInterceptor.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void validateIp(String ips, AccessControlListVO acl) {
    DebugUtils.Assert(acl != null, "the invalide null AccessControlListVO");
    Integer ipVer = acl.getIpVersion();
    if (!ipVer.equals(IPv6Constants.IPv4)) {
        throw new ApiMessageInterceptionException(argerr("not support the ip version %d", ipVer));
    }
    try {
        RangeSet<Long> ipRanges = IpRangeSet.listAllRanges(ips);
        String[] ipcount = ips.split(IP_SPLIT);
        if (ipRanges.asRanges().size() < ipcount.length) {
            throw new ApiMessageInterceptionException(argerr("%s duplicate/overlap ip entry with access-control-list group:%s", ips, acl.getUuid()));
        }
        for (Range<Long> range : ipRanges.asRanges()) {
            final Range<Long> frange = ContiguousSet.create(range, DiscreteDomain.longs()).range();
            String startIp = NetworkUtils.longToIpv4String(frange.lowerEndpoint());
            String endIp = NetworkUtils.longToIpv4String(frange.upperEndpoint());
            if (!validateIpRange(startIp, endIp)) {
                throw new ApiMessageInterceptionException(argerr("ip format only supports ip/iprange/cidr, but find %s", ips));
            }
            ipRanges.asRanges().stream().forEach(r -> {
                if (!frange.equals(r) && NetworkUtils.isIpv4RangeOverlap(startIp, endIp, NetworkUtils.longToIpv4String(r.lowerEndpoint()), NetworkUtils.longToIpv4String(r.upperEndpoint()))) {
                    throw new ApiMessageInterceptionException(argerr("ip range[%s, %s] is overlap with [%s, %s] in access-control-list group:%s",
                            startIp, endIp, NetworkUtils.longToIpv4String(r.lowerEndpoint()), NetworkUtils.longToIpv4String(r.upperEndpoint()), acl.getUuid()));
                }
            });
        }

    } catch (IllegalArgumentException e) {
        throw new ApiMessageInterceptionException(argerr("Invalid rule expression, the detail: %s", e.getMessage()));
    }

}
 
Example 7
Source File: LoadBalancerApiInterceptor.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void validateIp(String ips, AccessControlListVO acl) {
    DebugUtils.Assert(acl != null, "the invalide null AccessControlListVO");
    Integer ipVer = acl.getIpVersion();
    if (!ipVer.equals(IPv6Constants.IPv4)) {
        throw new ApiMessageInterceptionException(argerr("operation failure, not support the ip version %d", ipVer));
    }
    try {
        RangeSet<Long> ipRanges = IpRangeSet.listAllRanges(ips);
        String[] ipcount = ips.split(IP_SPLIT);
        if (ipRanges.asRanges().size() < ipcount.length) {
            throw new ApiMessageInterceptionException(argerr("operation failure, duplicate/overlap ip entry in %s of accesscontrol list group:%s", ips, acl.getUuid()));
        }
        for (Range<Long> range : ipRanges.asRanges()) {
            final Range<Long> frange = ContiguousSet.create(range, DiscreteDomain.longs()).range();
            String startIp = NetworkUtils.longToIpv4String(frange.lowerEndpoint());
            String endIp = NetworkUtils.longToIpv4String(frange.upperEndpoint());
            if (!validateIpRange(startIp, endIp)) {
                throw new ApiMessageInterceptionException(argerr("operation failure, ip format only supports ip/iprange/cidr, but find %s", ips));
            }
            ipRanges.asRanges().stream().forEach(r -> {
                if (!frange.equals(r) && NetworkUtils.isIpv4RangeOverlap(startIp, endIp, NetworkUtils.longToIpv4String(r.lowerEndpoint()), NetworkUtils.longToIpv4String(r.upperEndpoint()))) {
                    throw new ApiMessageInterceptionException(argerr("ip range[%s, %s] is overlap with start ip:%s, end ip: %s of access-control-list group:%s",
                            startIp, endIp, NetworkUtils.longToIpv4String(r.lowerEndpoint()), NetworkUtils.longToIpv4String(r.upperEndpoint()), acl.getUuid()));
                }
            });
        }

    } catch (IllegalArgumentException e) {
        throw new ApiMessageInterceptionException(argerr("Invalid rule expression, the detail: %s", e.getMessage()));
    }

}
 
Example 8
Source File: UidRange.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static LinkedList<Range<MessageUid>> mergeContiguousRanges(RangeSet<MessageUid> rangeSet) {
    LinkedList<Range<MessageUid>> mergedRanges = new LinkedList<>();
    
    for (Range<MessageUid> range: rangeSet.asRanges()) {
        Range<MessageUid> previous = mergedRanges.peekLast();
        if (rangesShouldBeMerged(range, previous)) {
            replaceLastRange(mergedRanges, mergeRanges(range, previous));
        } else {
            mergedRanges.add(range);
        }
    }
    return mergedRanges;
}
 
Example 9
Source File: FancierDiffLogger.java    From tac-kbp-eal with MIT License 5 votes vote down vote up
private String context(final String originalDocText, final Response response) {
  // [1,3], [2,5], [8,10] => [1,5], [8,10]
  final List<CharOffsetSpan> charSpans = justificationSpans(response);
  final List<CharOffsetSpan> unitedSpans = Lists.newArrayList();

  // use RangeSet to do this
  final RangeSet<Integer> disconnected = TreeRangeSet.create();
  for (CharOffsetSpan charSpan : charSpans) {
    int startInclusive = charSpan.startInclusive();
    int endInclusive = charSpan.endInclusive();
    startInclusive = (startInclusive - 100) >= 0 ? startInclusive - 100 : 0;
    endInclusive =
        (endInclusive + 100) < originalDocText.length() ? endInclusive + 100 : endInclusive;
    disconnected.add(Range.closed(startInclusive, endInclusive));
  }
  for (Range<Integer> range : disconnected.asRanges()) {
    unitedSpans.add(CharOffsetSpan.fromOffsetsOnly(range.lowerEndpoint(), range.upperEndpoint()));
  }
  Collections.sort(unitedSpans);
  String justificationsString = "";
  if (unitedSpans.get(0).startInclusive() != 0) {
    justificationsString += "[.....]";
  }
  for (CharOffsetSpan span : unitedSpans) {
    justificationsString +=
        originalDocText.substring(span.startInclusive(), span.endInclusive() + 1);
    justificationsString += "[.....]";
  }
  return justificationsString;
}
 
Example 10
Source File: LengthRestrictedTypeBuilder.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Set a new length constraint.
 *
 * @param constraint Constraint metadata
 * @param ranges Allowed ranges
 * @throws IllegalStateException if the constraint has already been set
 * @throws InvalidLengthConstraintException if one of the proposed ranges does not overlap with supertype
 * @throws NullPointerException if any of the arguments is null
 */
public final void setLengthConstraint(final @NonNull ConstraintMetaDefinition constraint,
        final @NonNull List<ValueRange> ranges) throws InvalidLengthConstraintException {
    Preconditions.checkState(lengthConstraint == null, "Length constraint already defined as %s", lengthConstraint);
    final LengthConstraint baseLengths = findLenghts();
    if (ranges.isEmpty()) {
        lengthConstraint = baseLengths;
        return;
    }

    // Run through alternatives and resolve them against the base type
    requireNonNull(constraint);
    final Builder<Integer> builder = ImmutableRangeSet.builder();
    final Range<Integer> span = baseLengths.getAllowedRanges().span();

    for (ValueRange c : ranges) {
        builder.add(Range.closed(resolveLength(c.lowerBound(), span), resolveLength(c.upperBound(), span)));
    }


    // Now verify if new ranges are strict subset of base ranges
    final RangeSet<Integer> allowed = builder.build();
    final RangeSet<Integer> baseRanges = baseLengths.getAllowedRanges();
    for (Range<Integer> range : allowed.asRanges()) {
        if (!baseRanges.encloses(range)) {
            throw new InvalidLengthConstraintException("Range %s is not a subset of parent constraint %s", range,
                baseRanges);
        }
    }

    lengthConstraint = new ResolvedLengthConstraint(constraint, allowed);
    touch();
}
 
Example 11
Source File: CrontabEntry.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private String fieldToString(RangeSet<Integer> rangeSet, Range<Integer> coveringRange) {
  if (rangeSet.asRanges().size() == 1 && rangeSet.encloses(coveringRange)) {
    return "*";
  }
  List<String> components = Lists.newArrayList();
  for (Range<Integer> range : rangeSet.asRanges()) {
    ContiguousSet<Integer> set = ContiguousSet.create(range, DiscreteDomain.integers());
    if (set.size() == 1) {
      components.add(set.first().toString());
    } else {
      components.add(set.first() + "-" + set.last());
    }
  }
  return String.join(",", components);
}
 
Example 12
Source File: RangeSetSerializerConverter.java    From batfish with Apache License 2.0 4 votes vote down vote up
@Override
public @Nonnull Set<Range<Comparable<?>>> convert(RangeSet<Comparable<?>> value) {
  return value.asRanges();
}
 
Example 13
Source File: YangParserTest.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testTypedefRangesResolving() throws ParseException {
    final LeafSchemaNode int32Leaf = (LeafSchemaNode) foo.getDataChildByName(QName.create(foo.getQNameModule(),
        "int32-leaf"));

    final Int32TypeDefinition leafType = (Int32TypeDefinition) int32Leaf.getType();
    assertEquals(QName.create(FOO, "int32-ext2"), leafType.getQName());
    assertEquals(Optional.of("mile"), leafType.getUnits());
    assertEquals(Optional.of("11"), leafType.getDefaultValue());

    final RangeSet<? extends Number> rangeset = leafType.getRangeConstraint().get().getAllowedRanges();
    final Set<? extends Range<? extends Number>> ranges = rangeset.asRanges();
    assertEquals(1, ranges.size());

    final Range<? extends Number> range = ranges.iterator().next();
    assertEquals(12, range.lowerEndpoint().intValue());
    assertEquals(20, range.upperEndpoint().intValue());

    final Int32TypeDefinition firstBaseType = leafType.getBaseType();
    assertEquals(QName.create(BAR, "int32-ext2"), firstBaseType.getQName());
    assertEquals(Optional.of("mile"), firstBaseType.getUnits());
    assertEquals(Optional.of("11"), firstBaseType.getDefaultValue());

    final RangeSet<? extends Number> firstRangeset = firstBaseType.getRangeConstraint().get().getAllowedRanges();
    final Set<? extends Range<? extends Number>> baseRanges = firstRangeset.asRanges();
    assertEquals(2, baseRanges.size());

    final Iterator<? extends Range<? extends Number>> it = baseRanges.iterator();
    final Range<? extends Number> baseTypeRange1 = it.next();
    assertEquals(3, baseTypeRange1.lowerEndpoint().intValue());
    assertEquals(9, baseTypeRange1.upperEndpoint().intValue());
    final Range<? extends Number> baseTypeRange2 = it.next();
    assertEquals(11, baseTypeRange2.lowerEndpoint().intValue());
    assertEquals(20, baseTypeRange2.upperEndpoint().intValue());

    final Int32TypeDefinition secondBaseType = firstBaseType.getBaseType();
    final QName baseQName = secondBaseType.getQName();
    assertEquals("int32-ext1", baseQName.getLocalName());
    assertEquals(BAR, baseQName.getModule());
    assertEquals(Optional.empty(), secondBaseType.getUnits());
    assertEquals(Optional.empty(), secondBaseType.getDefaultValue());

    final Set<? extends Range<? extends Number>> secondRanges = secondBaseType.getRangeConstraint().get()
            .getAllowedRanges().asRanges();
    assertEquals(1, secondRanges.size());
    final Range<? extends Number> secondRange = secondRanges.iterator().next();
    assertEquals(2, secondRange.lowerEndpoint().intValue());
    assertEquals(20, secondRange.upperEndpoint().intValue());

    assertEquals(BaseTypes.int32Type(), secondBaseType.getBaseType());
}