com.google.common.collect.RangeSet Java Examples
The following examples show how to use
com.google.common.collect.RangeSet.
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: MarkerConfigXmlParser.java From tracecompass with Eclipse Public License 2.0 | 6 votes |
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 #2
Source File: Formatter.java From java-n-IDE-for-Android with Apache License 2.0 | 6 votes |
/** * 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 #3
Source File: DateRangeRules.java From Bats with Apache License 2.0 | 6 votes |
/** 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 #4
Source File: DateRangeRules.java From Quicksql with MIT License | 6 votes |
/** 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 File: PaloAltoConfiguration.java From batfish with Apache License 2.0 | 6 votes |
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 #6
Source File: DateRangeRules.java From Bats with Apache License 2.0 | 6 votes |
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 #7
Source File: Formatter.java From java-n-IDE-for-Android with Apache License 2.0 | 6 votes |
/** * 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 #8
Source File: Formatter.java From javaide with GNU General Public License v3.0 | 6 votes |
/** * 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 #9
Source File: GoogleJavaFormatter.java From git-code-format-maven-plugin with MIT License | 6 votes |
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
Source File: QuotaManager.java From attic-aurora with Apache License 2.0 | 6 votes |
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 #11
Source File: RemoveUnusedImports.java From google-java-format with Apache License 2.0 | 6 votes |
/** 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 #12
Source File: RangeSetDeserializer.java From jackson-datatypes-collections with Apache License 2.0 | 6 votes |
@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 #13
Source File: F5BigipConfiguration.java From batfish with Apache License 2.0 | 6 votes |
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 #14
Source File: Networking.java From brooklyn-server with Apache License 2.0 | 6 votes |
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
Source File: RangeRestrictedTypeBuilder.java From yangtools with Eclipse Public License 1.0 | 6 votes |
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 File: NetworkingUtilsTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Test public void testPortRulesToRanges() throws Exception { RangeSet<Integer> actualRangeSet = Networking.portRulesToRanges(ImmutableList.of( "22", "23", "5000-6000", "8081", "80-90", "90-100", "23", "8081")); Asserts.assertEquals(actualRangeSet, ImmutableRangeSet.<Integer>builder() .add(Range.closed(22, 22)) .add(Range.closed(23, 23)) .add(Range.closed(80, 100)) .add(Range.closed(5000, 6000)) .add(Range.closed(8081, 8081)) .build()); }
Example #17
Source File: UidRange.java From james-project with Apache License 2.0 | 5 votes |
private static RangeSet<MessageUid> createSortedRangeSet(List<UidRange> ranges) { RangeSet<MessageUid> rangeSet = TreeRangeSet.create(); for (UidRange range: ranges) { rangeSet.add(Range.closed(range.getLowVal(), range.getHighVal())); } return rangeSet; }
Example #18
Source File: IdentifierPerType.java From tassal with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static final void addToMap( final Map<String, RangeSet<Integer>> identifiers, final ASTNode node, final String identifier) { final int startPosition = node.getStartPosition(); final Range<Integer> nodeRange = Range.closedOpen(startPosition, startPosition + node.getLength()); RangeSet<Integer> idRanges = identifiers.get(identifier); if (idRanges == null) { idRanges = TreeRangeSet.create(); identifiers.put(identifier, idRanges); } idRanges.add(nodeRange); }
Example #19
Source File: JavaInput.java From google-java-format with Apache License 2.0 | 5 votes |
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 #20
Source File: LineRangesToCharRangesTest.java From google-java-format with Apache License 2.0 | 5 votes |
@SafeVarargs final Set<Range<Integer>> getCharRanges(String input, Range<Integer>... ranges) { RangeSet<Integer> rangeSet = TreeRangeSet.create(); for (Range<Integer> range : ranges) { rangeSet.add(range); } return Formatter.lineRangesToCharRanges(input, rangeSet).asRanges(); }
Example #21
Source File: IdentifierPerType.java From codemining-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static final void addToMap( final Map<String, RangeSet<Integer>> identifiers, final ASTNode node, final String identifier) { final int startPosition = node.getStartPosition(); final Range<Integer> nodeRange = Range.closedOpen(startPosition, startPosition + node.getLength()); RangeSet<Integer> idRanges = identifiers.get(identifier); if (idRanges == null) { idRanges = TreeRangeSet.create(); identifiers.put(identifier, idRanges); } idRanges.add(nodeRange); }
Example #22
Source File: TransformationToTransition.java From batfish with Apache License 2.0 | 5 votes |
private static EraseAndSet assignIpFromPool(BDDInteger var, RangeSet<Ip> ranges) { BDD erase = Arrays.stream(var.getBitvec()).reduce(var.getFactory().one(), BDD::and); BDD setValue = ranges.asRanges().stream() .map(range -> var.range(range.lowerEndpoint().asLong(), range.upperEndpoint().asLong())) .reduce(var.getFactory().zero(), BDD::or); return new EraseAndSet(erase, setValue); }
Example #23
Source File: CrontabEntry.java From attic-aurora with Apache License 2.0 | 5 votes |
private static void checkEnclosed( String fieldName, Range<Integer> fieldEnclosure, RangeSet<Integer> field) { checkArgument(fieldEnclosure.encloses(field.span()), String.format( "Bad specification for field %s: span(%s) = %s is not enclosed by boundary %s.", fieldName, field, field.span(), fieldEnclosure)); }
Example #24
Source File: JavaIdentifierAnnotatedTokenizer.java From tassal with BSD 3-Clause "New" or "Revised" License | 5 votes |
private boolean isInSet(final String token, final Range<Integer> tokenRange, final Map<String, RangeSet<Integer>> set) { if (!set.containsKey(token)) { return false; } // TODO: Check if in scope return true; }
Example #25
Source File: PaloAltoConfiguration.java From batfish with Apache License 2.0 | 5 votes |
@Nonnull private RangeSet<Ip> ipRangeSetFromRuleEndpoints( Collection<RuleEndpoint> endpoints, Vsys vsys, Warnings w) { RangeSet<Ip> rangeSet = TreeRangeSet.create(); endpoints.stream() .map(endpoint -> ruleEndpointToIpRangeSet(endpoint, vsys, w)) .forEach(rangeSet::addAll); return ImmutableRangeSet.copyOf(rangeSet); }
Example #26
Source File: PaloAltoConfiguration.java From batfish with Apache License 2.0 | 5 votes |
private List<TransformationStep> getSourceTransformationSteps(NatRule rule, Vsys vsys) { List<RuleEndpoint> translatedSrcAddrs = Optional.ofNullable(rule.getSourceTranslation()) .map(SourceTranslation::getDynamicIpAndPort) .map(DynamicIpAndPort::getTranslatedAddresses) .orElse(null); if (translatedSrcAddrs == null) { // No source translation return ImmutableList.of(); } RangeSet<Ip> pool = ipRangeSetFromRuleEndpoints(translatedSrcAddrs, vsys, _w); if (pool.isEmpty()) { // Can't apply a source 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 source translation because its source translation pool is empty", rule.getName(), vsys.getName())); return ImmutableList.of(); } // Create steps to transform src IP and port return ImmutableList.of( new AssignIpAddressFromPool(TransformationType.SOURCE_NAT, IpField.SOURCE, pool), TransformationStep.assignSourcePort( NamedPort.EPHEMERAL_LOWEST.number(), NamedPort.EPHEMERAL_HIGHEST.number())); }
Example #27
Source File: AccessControlListApiInterceptor.java From zstack with Apache License 2.0 | 5 votes |
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 #28
Source File: ConfigurableMarkerEventSource.java From tracecompass with Eclipse Public License 2.0 | 5 votes |
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 #29
Source File: RangeRestrictedTypeBuilder.java From yangtools with Eclipse Public License 1.0 | 5 votes |
@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 #30
Source File: CrontabEntry.java From attic-aurora with Apache License 2.0 | 5 votes |
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); }