Java Code Examples for com.google.common.collect.RangeSet

The following examples show how to use com.google.common.collect.RangeSet. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Bats   Source File: DateRangeRules.java    License: Apache License 2.0 6 votes vote down vote up
/** Replaces calls to EXTRACT, FLOOR and CEIL in an expression. */
@VisibleForTesting
public static RexNode replaceTimeUnits(RexBuilder rexBuilder, RexNode e, String timeZone) {
    ImmutableSortedSet<TimeUnitRange> timeUnits = extractTimeUnits(e);
    if (!timeUnits.contains(TimeUnitRange.YEAR)) {
        // Case when we have FLOOR or CEIL but no extract on YEAR.
        // Add YEAR as TimeUnit so that FLOOR gets replaced in first iteration
        // with timeUnit YEAR.
        timeUnits = ImmutableSortedSet.<TimeUnitRange> naturalOrder().addAll(timeUnits).add(TimeUnitRange.YEAR)
                .build();
    }
    final Map<RexNode, RangeSet<Calendar>> operandRanges = new HashMap<>();
    for (TimeUnitRange timeUnit : timeUnits) {
        e = e.accept(new ExtractShuttle(rexBuilder, timeUnit, operandRanges, timeUnits, timeZone));
    }
    return e;
}
 
Example 2
Source Project: Bats   Source File: DateRangeRules.java    License: 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 3
Source Project: batfish   Source File: PaloAltoConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
private List<TransformationStep> getDestinationTransformationSteps(NatRule rule, Vsys vsys) {
  RuleEndpoint translatedDstAddr =
      Optional.ofNullable(rule.getDestinationTranslation())
          .map(DestinationTranslation::getTranslatedAddress)
          .orElse(null);
  if (translatedDstAddr == null) {
    // No destination translation
    return ImmutableList.of();
  }

  RangeSet<Ip> pool = ruleEndpointToIpRangeSet(translatedDstAddr, vsys, _w);
  if (pool.isEmpty()) {
    // Can't apply a dest IP translation with empty IP pool
    // TODO: Check real behavior in this scenario
    _w.redFlag(
        String.format(
            "NAT rule %s of VSYS %s will not apply destination translation because its destination translation pool is empty",
            rule.getName(), vsys.getName()));
    return ImmutableList.of();
  }

  // Create step to transform dst IP
  return ImmutableList.of(
      new AssignIpAddressFromPool(TransformationType.DEST_NAT, IpField.DESTINATION, pool));
}
 
Example 4
Source Project: Quicksql   Source File: DateRangeRules.java    License: MIT License 6 votes vote down vote up
/** Replaces calls to EXTRACT, FLOOR and CEIL in an expression. */
@VisibleForTesting
public static RexNode replaceTimeUnits(RexBuilder rexBuilder, RexNode e,
    String timeZone) {
  ImmutableSortedSet<TimeUnitRange> timeUnits = extractTimeUnits(e);
  if (!timeUnits.contains(TimeUnitRange.YEAR)) {
    // Case when we have FLOOR or CEIL but no extract on YEAR.
    // Add YEAR as TimeUnit so that FLOOR gets replaced in first iteration
    // with timeUnit YEAR.
    timeUnits = ImmutableSortedSet.<TimeUnitRange>naturalOrder()
        .addAll(timeUnits).add(TimeUnitRange.YEAR).build();
  }
  final Map<RexNode, RangeSet<Calendar>> operandRanges = new HashMap<>();
  for (TimeUnitRange timeUnit : timeUnits) {
    e = e.accept(
        new ExtractShuttle(rexBuilder, timeUnit, operandRanges, timeUnits,
            timeZone));
  }
  return e;
}
 
Example 5
Source Project: java-n-IDE-for-Android   Source File: Formatter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts zero-indexed, [closed, open) line ranges in the given source file to character ranges.
 */
public static RangeSet<Integer> lineRangesToCharRanges(
        String input, RangeSet<Integer> lineRanges) {
    List<Integer> lines = new ArrayList<>();
    Iterators.addAll(lines, Newlines.lineOffsetIterator(input));
    lines.add(input.length() + 1);

    final RangeSet<Integer> characterRanges = TreeRangeSet.create();
    for (Range<Integer> lineRange :
            lineRanges.subRangeSet(Range.closedOpen(0, lines.size() - 1)).asRanges()) {
        int lineStart = lines.get(lineRange.lowerEndpoint());
        // Exclude the trailing newline. This isn't strictly necessary, but handling blank lines
        // as empty ranges is convenient.
        int lineEnd = lines.get(lineRange.upperEndpoint()) - 1;
        Range<Integer> range = Range.closedOpen(lineStart, lineEnd);
        characterRanges.add(range);
    }
    return characterRanges;
}
 
Example 6
Source Project: java-n-IDE-for-Android   Source File: Formatter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Emit a list of {@link Replacement}s to convert from input to output.
 *
 * @param input           the input compilation unit
 * @param characterRanges the character ranges to reformat
 * @return a list of {@link Replacement}s, sorted from low index to high index, without overlaps
 * @throws FormatterException if the input string cannot be parsed
 */
public ImmutableList<Replacement> getFormatReplacements(
        String input, Collection<Range<Integer>> characterRanges) throws FormatterException {
    JavaInput javaInput = new JavaInput(input);

    // TODO(cushon): this is only safe because the modifier ordering doesn't affect whitespace,
    // and doesn't change the replacements that are output. This is not true in general for
    // 'de-linting' changes (e.g. import ordering).
    javaInput = ModifierOrderer.reorderModifiers(javaInput, characterRanges);

    String lineSeparator = Newlines.guessLineSeparator(input);
    JavaOutput javaOutput =
            new JavaOutput(lineSeparator, javaInput, new JavaCommentsHelper(lineSeparator, options));
    try {
        format(javaInput, javaOutput, options);
    } catch (FormattingError e) {
        throw new FormatterException(e.diagnostics());
    }
    RangeSet<Integer> tokenRangeSet = javaInput.characterRangesToTokenRanges(characterRanges);
    return javaOutput.getFormatReplacements(tokenRangeSet);
}
 
Example 7
Source Project: javaide   Source File: Formatter.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Converts zero-indexed, [closed, open) line ranges in the given source file to character ranges.
 */
public static RangeSet<Integer> lineRangesToCharRanges(
        String input, RangeSet<Integer> lineRanges) {
    List<Integer> lines = new ArrayList<>();
    Iterators.addAll(lines, Newlines.lineOffsetIterator(input));
    lines.add(input.length() + 1);

    final RangeSet<Integer> characterRanges = TreeRangeSet.create();
    for (Range<Integer> lineRange :
            lineRanges.subRangeSet(Range.closedOpen(0, lines.size() - 1)).asRanges()) {
        int lineStart = lines.get(lineRange.lowerEndpoint());
        // Exclude the trailing newline. This isn't strictly necessary, but handling blank lines
        // as empty ranges is convenient.
        int lineEnd = lines.get(lineRange.upperEndpoint()) - 1;
        Range<Integer> range = Range.closedOpen(lineStart, lineEnd);
        characterRanges.add(range);
    }
    return characterRanges;
}
 
Example 8
Source Project: attic-aurora   Source File: QuotaManager.java    License: Apache License 2.0 6 votes vote down vote up
private static Predicate<IAssignedTask> buildNonUpdatingTasksFilter(
    final Map<IJobKey, IJobUpdateInstructions> roleJobUpdates) {

  return task -> {
    Optional<IJobUpdateInstructions> update = Optional.ofNullable(
        roleJobUpdates.get(task.getTask().getJob()));

    if (update.isPresent()) {
      IJobUpdateInstructions instructions = update.get();
      RangeSet<Integer> initialInstances = getInstanceIds(instructions.getInitialState());
      RangeSet<Integer> desiredInstances = getInstanceIds(instructions.isSetDesiredState()
          ? ImmutableSet.of(instructions.getDesiredState())
          : ImmutableSet.of());

      int instanceId = task.getInstanceId();
      return !initialInstances.contains(instanceId) && !desiredInstances.contains(instanceId);
    }
    return true;
  };
}
 
Example 9
Source Project: git-code-format-maven-plugin   Source File: GoogleJavaFormatter.java    License: MIT License 6 votes vote down vote up
private String doFormat(String unformattedContent, LineRanges lineRanges)
    throws FormatterException {
  if (options.isFixImportsOnly()) {
    if (!lineRanges.isAll()) {
      return unformattedContent;
    }
    return fixImports(unformattedContent);
  }
  if (lineRanges.isAll()) {
    return fixImports(formatter.formatSource(unformattedContent));
  }

  RangeSet<Integer> charRangeSet =
      Formatter.lineRangesToCharRanges(unformattedContent, lineRanges.rangeSet());
  return formatter.formatSource(unformattedContent, charRangeSet.asRanges());
}
 
Example 10
@Override
public RangeSet<Comparable<?>> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    if (genericRangeListType == null) {
        throw new JsonParseException(p, "RangeSetJsonSerializer was not contextualized (no deserialize target type). " +
                "You need to specify the generic type down to the generic parameter of RangeSet.");
    } else {
        @SuppressWarnings("unchecked") final Iterable<Range<Comparable<?>>> ranges
                = (Iterable<Range<Comparable<?>>>) ctxt
                .findContextualValueDeserializer(genericRangeListType, null).deserialize(p, ctxt);
        ImmutableRangeSet.Builder<Comparable<?>> builder = ImmutableRangeSet.builder();
        for (Range<Comparable<?>> range : ranges) {
            builder.add(range);
        }
        return builder.build();
    }
}
 
Example 11
private static List<Marker> getMarkers(Element markerSet) {
    List<Marker> markers = new ArrayList<>();
    NodeList markerList = markerSet.getElementsByTagName(IMarkerConstants.MARKER);
    for (int i = 0; i < markerList.getLength(); i++) {
        Element markerElem = (Element) markerList.item(i);
        String name = markerElem.getAttribute(IMarkerConstants.NAME);
        String label = parseLabel(markerElem.getAttribute(IMarkerConstants.LABEL));
        String id = markerElem.getAttribute(IMarkerConstants.ID);
        String referenceId = markerElem.getAttribute(IMarkerConstants.REFERENCE_ID);
        String color = markerElem.getAttribute(IMarkerConstants.COLOR);
        double period = parsePeriod(markerElem.getAttribute(IMarkerConstants.PERIOD));
        String unit = parseUnit(markerElem.getAttribute(IMarkerConstants.UNIT));
        Range<Long> range = parseRange(markerElem.getAttribute(IMarkerConstants.RANGE));
        long offset = parseOffset(markerElem.getAttribute(IMarkerConstants.OFFSET));
        RangeSet<Long> indexRange = parseRangeSet(markerElem.getAttribute(IMarkerConstants.INDEX));
        PeriodicMarker marker = new PeriodicMarker(name, label, id, referenceId, color, period, unit, range, offset, indexRange);
        parseSubMarkers(markerElem, marker);
        markers.add(marker);
    }
    return markers;
}
 
Example 12
Source Project: batfish   Source File: F5BigipConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
private @Nonnull Optional<TransformationStep> computeOutgoingSnatPoolTransformation(
    SnatPool snatPool) {
  RangeSet<Ip> pool =
      ImmutableRangeSet.copyOf(
          snatPool.getMembers().stream()
              .map(_snatTranslations::get)
              .filter(Objects::nonNull)
              .map(SnatTranslation::getAddress)
              .filter(Objects::nonNull)
              .map(Range::singleton)
              .collect(ImmutableList.toImmutableList()));
  return pool.isEmpty()
      ? Optional.empty()
      : Optional.of(
          new ApplyAll(
              ASSIGN_EPHEMERAL_SOURCE_PORT,
              new AssignIpAddressFromPool(TransformationType.SOURCE_NAT, IpField.SOURCE, pool)));
}
 
Example 13
Source Project: google-java-format   Source File: RemoveUnusedImports.java    License: Apache License 2.0 6 votes vote down vote up
/** Applies the replacements to the given source, and re-format any edited javadoc. */
private static String applyReplacements(String source, RangeMap<Integer, String> replacements) {
  // save non-empty fixed ranges for reformatting after fixes are applied
  RangeSet<Integer> fixedRanges = TreeRangeSet.create();

  // Apply the fixes in increasing order, adjusting ranges to account for
  // earlier fixes that change the length of the source. The output ranges are
  // needed so we can reformat fixed regions, otherwise the fixes could just
  // be applied in descending order without adjusting offsets.
  StringBuilder sb = new StringBuilder(source);
  int offset = 0;
  for (Map.Entry<Range<Integer>, String> replacement : replacements.asMapOfRanges().entrySet()) {
    Range<Integer> range = replacement.getKey();
    String replaceWith = replacement.getValue();
    int start = offset + range.lowerEndpoint();
    int end = offset + range.upperEndpoint();
    sb.replace(start, end, replaceWith);
    if (!replaceWith.isEmpty()) {
      fixedRanges.add(Range.closedOpen(start, end));
    }
    offset += replaceWith.length() - (range.upperEndpoint() - range.lowerEndpoint());
  }
  return sb.toString();
}
 
Example 14
Source Project: brooklyn-server   Source File: Networking.java    License: Apache License 2.0 6 votes vote down vote up
public static RangeSet<Integer> portRulesToRanges(Collection<String> portRules) {
    RangeSet<Integer> result = TreeRangeSet.create();
    for (String portRule : portRules) {
        if (portRule.contains("-")) {
            String[] fromTo = portRule.split("-");
            checkArgument(fromTo.length == 2, "Invalid port range '%s'", portRule);
            checkArgument(Strings.countOccurrences(portRule, '-') == 1, "Invalid port range '%s'", portRule);
            checkArgument(Strings.isNonEmpty(fromTo[0]), "Invalid port range '%s'", portRule);
            checkArgument(Strings.isNonEmpty(fromTo[1]), "Invalid port range '%s'", portRule);
            result.add(closedRange(fromTo[0], fromTo[1]));
        } else {
            result.add(closedRange(portRule, portRule));
        }
    }
    return result;
}
 
Example 15
final RangeConstraint<N> calculateRangeConstraint(final RangeConstraint<N> baseRangeConstraint) {
    if (ranges == null) {
        return baseRangeConstraint;
    }

    // Run through alternatives and resolve them against the base type
    final RangeSet<N> baseRangeSet = baseRangeConstraint.getAllowedRanges();
    Verify.verify(!baseRangeSet.isEmpty(), "Base type %s does not define constraints", getBaseType());

    final Range<N> baseRange = baseRangeSet.span();
    final List<ValueRange> resolvedRanges = ensureResolvedRanges(ranges, baseRange);

    // Next up, ensure the of boundaries match base constraints
    final RangeSet<N> typedRanges = ensureTypedRanges(resolvedRanges, baseRange.lowerEndpoint().getClass());

    // Now verify if new ranges are strict subset of base ranges
    if (!baseRangeSet.enclosesAll(typedRanges)) {
        throw new InvalidRangeConstraintException(typedRanges,
            "Range constraint %s is not a subset of parent constraint %s", typedRanges, baseRangeSet);
    }

    return new ResolvedRangeConstraint<>(constraint, typedRanges);
}
 
Example 16
Source Project: Bats   Source File: DateRangeRules.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
ExtractShuttle(RexBuilder rexBuilder, TimeUnitRange timeUnit, Map<RexNode, RangeSet<Calendar>> operandRanges,
        ImmutableSortedSet<TimeUnitRange> timeUnitRanges, String timeZone) {
    this.rexBuilder = Objects.requireNonNull(rexBuilder);
    this.timeUnit = Objects.requireNonNull(timeUnit);
    Bug.upgrade("Change type to Map<RexNode, RangeSet<Calendar>> when" + " [CALCITE-1367] is fixed");
    this.operandRanges = Objects.requireNonNull(operandRanges);
    this.timeUnitRanges = Objects.requireNonNull(timeUnitRanges);
    this.timeZone = timeZone;
}
 
Example 17
Source Project: onos   Source File: EncodedDiscreteResources.java    License: Apache License 2.0 5 votes vote down vote up
static EncodedDiscreteResources of(Set<DiscreteResource> resources, DiscreteResourceCodec codec) {
    RangeSet<Integer> rangeSet = TreeRangeSet.create();
    resources.stream()
            .map(x -> x.valueAs(Object.class))
            .flatMap(Tools::stream)
            .map(x -> codec.encode(x))
            .map(Range::singleton)
            .map(x -> x.canonical(DiscreteDomain.integers()))
            .forEach(rangeSet::add);

    return new EncodedDiscreteResources(rangeSet, codec);
}
 
Example 18
Source Project: batfish   Source File: AddressObject.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns all addresses owned by this address object as an IP {@link RangeSet}. */
@Nonnull
public RangeSet<Ip> getAddressAsRangeSet() {
  if (_ip != null) {
    return ImmutableRangeSet.of(Range.singleton(_ip));
  } else if (_prefix != null) {
    return ImmutableRangeSet.of(
        Range.closed(_prefix.getPrefix().getStartIp(), _prefix.getPrefix().getEndIp()));
  } else if (_ipRange != null) {
    return ImmutableRangeSet.of(_ipRange);
  }
  return ImmutableRangeSet.of();
}
 
Example 19
Source Project: java-n-IDE-for-Android   Source File: SnippetFormatter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Runs the Google Java formatter on the given source, with only the given ranges specified.
 */
public List<Replacement> format(
        SnippetKind kind,
        String source,
        List<Range<Integer>> ranges,
        int initialIndent,
        boolean includeComments)
        throws FormatterException {
    RangeSet<Integer> rangeSet = TreeRangeSet.create();
    for (Range<Integer> range : ranges) {
        rangeSet.add(range);
    }
    if (includeComments) {
        if (kind != SnippetKind.COMPILATION_UNIT) {
            throw new IllegalArgumentException(
                    "comment formatting is only supported for compilation units");
        }
        return formatter.getFormatReplacements(source, ranges);
    }
    SnippetWrapper wrapper = snippetWrapper(kind, source, initialIndent);
    ranges = offsetRanges(ranges, wrapper.offset);

    String replacement = formatter.formatSource(wrapper.contents.toString(), ranges);
    replacement =
            replacement.substring(
                    wrapper.offset,
                    replacement.length() - (wrapper.contents.length() - wrapper.offset - source.length()));

    List<Replacement> replacements = toReplacements(source, replacement);
    List<Replacement> filtered = new ArrayList<>();
    for (Replacement r : replacements) {
        if (rangeSet.encloses(r.getReplaceRange())) {
            filtered.add(r);
        }
    }
    return filtered;
}
 
Example 20
Source Project: java-n-IDE-for-Android   Source File: JavaInput.java    License: Apache License 2.0 5 votes vote down vote up
public RangeSet<Integer> characterRangesToTokenRanges(Collection<Range<Integer>> characterRanges)
        throws FormatterException {
    RangeSet<Integer> tokenRangeSet = TreeRangeSet.create();
    for (Range<Integer> characterRange0 : characterRanges) {
        Range<Integer> characterRange = characterRange0.canonical(DiscreteDomain.integers());
        tokenRangeSet.add(
                characterRangeToTokenRange(
                        characterRange.lowerEndpoint(),
                        characterRange.upperEndpoint() - characterRange.lowerEndpoint()));
    }
    return tokenRangeSet;
}
 
Example 21
Source Project: javaide   Source File: SnippetFormatter.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Runs the Google Java formatter on the given source, with only the given ranges specified.
 */
public List<Replacement> format(
        SnippetKind kind,
        String source,
        List<Range<Integer>> ranges,
        int initialIndent,
        boolean includeComments)
        throws FormatterException {
    RangeSet<Integer> rangeSet = TreeRangeSet.create();
    for (Range<Integer> range : ranges) {
        rangeSet.add(range);
    }
    if (includeComments) {
        if (kind != SnippetKind.COMPILATION_UNIT) {
            throw new IllegalArgumentException(
                    "comment formatting is only supported for compilation units");
        }
        return formatter.getFormatReplacements(source, ranges);
    }
    SnippetWrapper wrapper = snippetWrapper(kind, source, initialIndent);
    ranges = offsetRanges(ranges, wrapper.offset);

    String replacement = formatter.formatSource(wrapper.contents.toString(), ranges);
    replacement =
            replacement.substring(
                    wrapper.offset,
                    replacement.length() - (wrapper.contents.length() - wrapper.offset - source.length()));

    List<Replacement> replacements = toReplacements(source, replacement);
    List<Replacement> filtered = new ArrayList<>();
    for (Replacement r : replacements) {
        if (rangeSet.encloses(r.getReplaceRange())) {
            filtered.add(r);
        }
    }
    return filtered;
}
 
Example 22
Source Project: attic-aurora   Source File: CrontabEntry.java    License: Apache License 2.0 5 votes vote down vote up
private RangeSet<Integer> parseMinute() {
  RangeSet<Integer> minutes = TreeRangeSet.create();
  for (String component : getComponents(rawMinute)) {
    minutes.addAll(parseComponent(MINUTE, component));
  }
  return ImmutableRangeSet.copyOf(minutes);
}
 
Example 23
Source Project: batfish   Source File: CumulusNcluConfigurationBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check that the given RangeSet is upper-bounded by {@code maxValue}, otherwise throw {@link
 * IllegalArgumentException}
 */
private static void checkUpperBound(RangeSet<? extends Number> rangeSet, long maxValue) {
  Range<? extends Number> range =
      Iterables.getFirst(rangeSet.asDescendingSetOfRanges(), Range.singleton(maxValue));
  assert range != null; // range set won't give us null ranges
  Number upperBound = range.upperEndpoint();
  checkArgument(
      range.upperBoundType() == BoundType.CLOSED
          ? upperBound.longValue() <= maxValue
          : upperBound.longValue() < maxValue,
      "Invalid range %s, max value allowed is %d",
      rangeSet,
      maxValue);
}
 
Example 24
Source Project: tutorials   Source File: GuavaRangeSetUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenImmutableRangeSet_whenQueryWithinRange_returnsSucessfully() {
    final RangeSet<Integer> numberRangeSet = ImmutableRangeSet.<Integer> builder()
 .add(Range.closed(0, 2))
 .add(Range.closed(3, 5))
 .add(Range.closed(6, 8)).build();

    assertTrue(numberRangeSet.contains(6));
    assertFalse(numberRangeSet.contains(15));
}
 
Example 25
@SuppressWarnings("unchecked")
private static <T extends Number & Comparable<T>> RangeSet<T> typedRanges(final List<ValueRange> ranges,
        final Class<? extends Number> clazz) {
    final Function<Number, ? extends Number> function = NumberUtil.converterTo(clazz);
    Preconditions.checkArgument(function != null, "Unsupported range class %s", clazz);

    final Builder<T> builder = ImmutableRangeSet.builder();

    for (ValueRange range : ranges) {
        if (!clazz.isInstance(range.lowerBound()) || !clazz.isInstance(range.upperBound())) {
            final Number min;
            final Number max;

            try {
                min = function.apply(range.lowerBound());
                max = function.apply(range.upperBound());
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(String.format("Constraint %s does not fit into range of %s",
                    range, clazz.getSimpleName()), e);
            }

            builder.add(Range.closed((T)min, (T)max));
        } else {
            builder.add(Range.closed((T) range.lowerBound(), (T)range.upperBound()));
        }
    }

    return builder.build();
}
 
Example 26
/**
 * 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 27
@SuppressWarnings("unchecked")
private static <T extends Number & Comparable<T>> RangeSet<T> ensureTypedRanges(final List<ValueRange> ranges,
        final Class<? extends Number> clazz) {
    final Builder<T> builder = ImmutableRangeSet.builder();
    for (ValueRange range : ranges) {
        if (!clazz.isInstance(range.lowerBound()) || !clazz.isInstance(range.upperBound())) {
            return typedRanges(ranges, clazz);
        }

        builder.add(Range.closed((T) range.lowerBound(), (T)range.upperBound()));
    }

    return builder.build();
}
 
Example 28
private static RangeSet<Long> parseRangeSet(String rangeSetAttr) {
    if (rangeSetAttr.isEmpty()) {
        return ImmutableRangeSet.of(Range.all());
    }
    RangeSet<Long> rangeSet = TreeRangeSet.create();
    String[] ranges = rangeSetAttr.split(","); //$NON-NLS-1$
    if (ranges.length == 0) {
        rangeSet.add(Range.all());
    } else {
        for (String range : ranges) {
            rangeSet.add(parseRange(range));
        }
    }
    return rangeSet;
}
 
Example 29
public ConfigurablePeriodicMarkerEventSource(Marker marker, @NonNull String category, @NonNull Reference reference, double period, long rollover, @NonNull RGBA evenColor, @NonNull RGBA oddColor, boolean foreground, long startIndex, @NonNull String label, RangeSet<Long> indexRange) {
    super(category, reference, period, rollover, evenColor, oddColor, foreground);
    fMarker = marker;
    fStartIndex = startIndex;
    fLabel = label;
    fIndexRange = indexRange;
    fMaxDuration = period;
}
 
Example 30
Source Project: zstack   Source File: AccessControlListApiInterceptor.java    License: 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()));
    }

}