com.google.common.collect.ImmutableRangeSet Java Examples
The following examples show how to use
com.google.common.collect.ImmutableRangeSet.
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: QuoteFilter.java From tac-kbp-eal with MIT License | 6 votes |
public void saveTo(ByteSink sink) throws IOException { final PrintWriter out = new PrintWriter(sink.asCharSink(Charsets.UTF_8).openBufferedStream()); out.println(docIdToBannedRegions.size()); for (final Map.Entry<Symbol, ImmutableRangeSet<Integer>> entry : docIdToBannedRegions .entrySet()) { out.println(entry.getKey()); final List<String> parts = Lists.newArrayList(); for (final Range<Integer> r : entry.getValue().asRanges()) { // we know by construction these ranges are bounded above and below parts.add(String.format("%d-%d", r.lowerEndpoint(), r.upperEndpoint())); } out.println(StringUtils.spaceJoiner().join(parts)); } out.close(); }
Example #2
Source File: CrontabEntry.java From attic-aurora with Apache License 2.0 | 6 votes |
private CrontabEntry( RangeSet<Integer> minute, RangeSet<Integer> hour, RangeSet<Integer> dayOfMonth, RangeSet<Integer> month, RangeSet<Integer> dayOfWeek) { checkEnclosed("minute", MINUTE, minute); checkEnclosed("hour", HOUR, hour); checkEnclosed("dayOfMonth", DAY_OF_MONTH, dayOfMonth); checkEnclosed("month", MONTH, month); checkEnclosed("dayOfWeek", DAY_OF_WEEK, dayOfWeek); this.minute = ImmutableRangeSet.copyOf(minute); this.hour = ImmutableRangeSet.copyOf(hour); this.dayOfMonth = ImmutableRangeSet.copyOf(dayOfMonth); this.month = ImmutableRangeSet.copyOf(month); this.dayOfWeek = ImmutableRangeSet.copyOf(dayOfWeek); checkArgument(hasWildcardDayOfMonth() || hasWildcardDayOfWeek(), "Specifying both dayOfWeek and dayOfMonth is not supported."); }
Example #3
Source File: DateRangeRules.java From Quicksql with MIT License | 6 votes |
private RexNode compareFloorCeil(SqlKind comparison, RexNode operand, RexLiteral timeLiteral, TimeUnitRange timeUnit, boolean floor) { RangeSet<Calendar> rangeSet = operandRanges.get(operand); if (rangeSet == null) { rangeSet = ImmutableRangeSet.<Calendar>of().complement(); } final RangeSet<Calendar> s2 = TreeRangeSet.create(); final Calendar c = timestampValue(timeLiteral); final Range<Calendar> range = floor ? floorRange(timeUnit, comparison, c) : ceilRange(timeUnit, comparison, c); s2.add(range); // Intersect old range set with new. s2.removeAll(rangeSet.complement()); operandRanges.put(operand, ImmutableRangeSet.copyOf(s2)); if (range.isEmpty()) { return rexBuilder.makeLiteral(false); } return toRex(operand, range); }
Example #4
Source File: MarkerTest.java From tracecompass with Eclipse Public License 2.0 | 6 votes |
/** * Test the PeriodicMarker constructor */ @Test public void testConstructor() { PeriodicMarker marker = new PeriodicMarker("name", "label", "id", "referenceid", "color", 1.0, "ms", Range.atLeast(0L), 0L, ImmutableRangeSet.of(Range.all())); assertEquals("name", marker.getName()); assertEquals("label", marker.getLabel()); assertEquals("id", marker.getId()); assertEquals("referenceid", marker.getReferenceId()); assertEquals("color", marker.getColor()); assertEquals(1.0, marker.getPeriod(), 0); assertEquals("ms", marker.getUnit()); assertEquals(Range.atLeast(0L), marker.getRange()); assertEquals(0L, marker.getOffset()); assertEquals(ImmutableRangeSet.of(Range.all()), marker.getIndexRange()); assertEquals(0, marker.getSubMarkers().size()); }
Example #5
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 #6
Source File: DateRangeRules.java From calcite with Apache License 2.0 | 6 votes |
private RexNode compareFloorCeil(SqlKind comparison, RexNode operand, RexLiteral timeLiteral, TimeUnitRange timeUnit, boolean floor) { RangeSet<Calendar> rangeSet = operandRanges.get(operand); if (rangeSet == null) { rangeSet = ImmutableRangeSet.<Calendar>of().complement(); } final RangeSet<Calendar> s2 = TreeRangeSet.create(); final Calendar c = timestampValue(timeLiteral); final Range<Calendar> range = floor ? floorRange(timeUnit, comparison, c) : ceilRange(timeUnit, comparison, c); s2.add(range); // Intersect old range set with new. s2.removeAll(rangeSet.complement()); operandRanges.put(operand, ImmutableRangeSet.copyOf(s2)); if (range.isEmpty()) { return rexBuilder.makeLiteral(false); } return toRex(operand, range); }
Example #7
Source File: TypeTest.java From yangtools with Eclipse Public License 1.0 | 6 votes |
@Test public void exceptionTest() { final UnresolvedNumber min = UnresolvedNumber.min(); final UnresolvedNumber max = UnresolvedNumber.max(); final EnumPair enumPair = EnumPairBuilder.create("enum1", 1).setDescription("description") .setReference("reference").setUnknownSchemaNodes(mock(UnknownSchemaNode.class)).build(); final RangeSet<Integer> rangeset = ImmutableRangeSet.of(Range.closed(1, 2)); final InvalidRangeConstraintException invalidRangeConstraintException = new InvalidRangeConstraintException( rangeset, "error msg", "other important messages"); assertSame(rangeset, invalidRangeConstraintException.getOffendingRanges()); final InvalidBitDefinitionException invalidBitDefinitionException = new InvalidBitDefinitionException( BIT_A, "error msg", "other important messages"); assertEquals(invalidBitDefinitionException.getOffendingBit(), BIT_A); final InvalidEnumDefinitionException invalidEnumDefinitionException = new InvalidEnumDefinitionException( enumPair, "error msg", "other important messages"); assertEquals(invalidEnumDefinitionException.getOffendingEnum(), enumPair); }
Example #8
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 #9
Source File: QuoteFilter.java From tac-kbp-eal with MIT License | 6 votes |
private ResponseMapping computeResponseMapping(final ArgumentOutput input) { final ImmutableRangeSet<Integer> bannedRegions = docIdToBannedRegions.get(input.docId()); if (bannedRegions == null) { throw new RuntimeException(String.format( "QuoteFilter does not know about document ID %s", input.docId())); } final ImmutableSet.Builder<Response> toDeleteB = ImmutableSet.builder();; for (final Response response : input.responses()) { if (isInQuote(input.docId(), response.baseFiller()) || isInQuote(input.docId(), response.canonicalArgument().charOffsetSpan())) { toDeleteB.add(response); } } final ImmutableSet<Response> toDelete = toDeleteB.build(); log.info("For document {}, filtered out {} responses which were in quoted regions", input.docId(), toDelete.size()); return ResponseMapping.create(ImmutableMap.<Response,Response>of(), toDelete); }
Example #10
Source File: DateRangeRules.java From Bats with Apache License 2.0 | 6 votes |
private RexNode compareFloorCeil(SqlKind comparison, RexNode operand, RexLiteral timeLiteral, TimeUnitRange timeUnit, boolean floor) { RangeSet<Calendar> rangeSet = operandRanges.get(operand); if (rangeSet == null) { rangeSet = ImmutableRangeSet.<Calendar> of().complement(); } final RangeSet<Calendar> s2 = TreeRangeSet.create(); final Calendar c = timestampValue(timeLiteral); final Range<Calendar> range = floor ? floorRange(timeUnit, comparison, c) : ceilRange(timeUnit, comparison, c); s2.add(range); // Intersect old range set with new. s2.removeAll(rangeSet.complement()); operandRanges.put(operand, ImmutableRangeSet.copyOf(s2)); if (range.isEmpty()) { return rexBuilder.makeLiteral(false); } return toRex(operand, range); }
Example #11
Source File: TestQuoteFilter.java From tac-kbp-eal with MIT License | 6 votes |
@Test public void testQuotedRegionComputation() throws IOException { final Map<String, ImmutableRangeSet<Integer>> testCases = ImmutableMap.of( "Foo <quote>bar <quote>baz</quote> <quote>meep</quote></quote> blah <quote>another</quote>", ImmutableRangeSet.<Integer>builder().add(Range.closed(4, 60)).add(Range.closed(67, 88)) .build(), "<quote>lalala</quote>", ImmutableRangeSet.of(Range.closed(0, 20)), "No quotes!", ImmutableRangeSet.<Integer>of()); for (final Map.Entry<String, ImmutableRangeSet<Integer>> entry : testCases.entrySet()) { final Symbol docid = Symbol.from("dummy"); final QuoteFilter reference = QuoteFilter.createFromBannedRegions(ImmutableMap.of(docid, entry.getValue())); final QuoteFilter computed = QuoteFilter.createFromOriginalText(ImmutableMap.of(docid, CharSource.wrap(entry.getKey()))); assertEquals(reference, computed); } }
Example #12
Source File: QuoteFilter.java From tac-kbp-eal with MIT License | 6 votes |
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 #13
Source File: AddressObject.java From batfish with Apache License 2.0 | 5 votes |
/** 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 #14
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> 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 #15
Source File: AddressGroup.java From batfish with Apache License 2.0 | 5 votes |
/** * Returns a {@link com.google.common.collect.RangeSet} containing the union of all addresses * owned by members. Returns empty RangeSet if there are no members. */ public RangeSet<Ip> getIpRangeSet( Map<String, AddressObject> addressObjects, Map<String, AddressGroup> addressGroups) { RangeSet<Ip> rangeSet = TreeRangeSet.create(); getDescendantObjects(addressObjects, addressGroups, new HashSet<>()).stream() .map(addrObjName -> addressObjects.get(addrObjName).getAddressAsRangeSet()) .forEach(rangeSet::addAll); return ImmutableRangeSet.copyOf(rangeSet); }
Example #16
Source File: LengthRestrictedTypeBuilder.java From yangtools with Eclipse Public License 1.0 | 5 votes |
/** * 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 #17
Source File: Updates.java From attic-aurora with Apache License 2.0 | 5 votes |
/** * Creates a range set representing all instance IDs represented by a set of instance * configurations included in a job update. * * @param configs Job update components. * @return A range set representing the instance IDs mentioned in instance groupings. */ public static ImmutableRangeSet<Integer> getInstanceIds(Set<IInstanceTaskConfig> configs) { ImmutableRangeSet.Builder<Integer> builder = ImmutableRangeSet.builder(); for (IInstanceTaskConfig config : configs) { for (IRange range : config.getInstances()) { builder.add(Range.closed(range.getFirst(), range.getLast())); } } return builder.build(); }
Example #18
Source File: Numbers.java From attic-aurora with Apache License 2.0 | 5 votes |
/** * Performs {@link #toRange(IRange)} for a collection of ranges, and convert the result to a set * of integers. * * @param ranges Ranges to convert. * @return A set representing {@code ranges}. */ public static Set<Integer> rangesToInstanceIds(Iterable<IRange> ranges) { ImmutableRangeSet.Builder<Integer> instanceIds = ImmutableRangeSet.builder(); for (IRange range : ranges) { instanceIds.add(toRange(range)); } return instanceIds.build().asSet(DiscreteDomain.integers()); }
Example #19
Source File: GuavaRangeSetUnitTest.java From tutorials with MIT License | 5 votes |
@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 #20
Source File: NumberSpace.java From batfish with Apache License 2.0 | 5 votes |
/** Intersect two number spaces together. */ public final S intersection(S other) { return newBuilder() .including( other._rangeset.asRanges().stream() .map(_rangeset::subRangeSet) // intersect individual ranges with _rangeset .map(RangeSet::asRanges) // flatten each intersection result to set of ranges .flatMap(Set::stream) // stream for collection .collect(ImmutableRangeSet.toImmutableRangeSet())) .build(); }
Example #21
Source File: F5BigipConfiguration.java From batfish with Apache License 2.0 | 5 votes |
private @Nonnull TransformationStep computeVirtualIncomingPoolMemberTransformation( PoolMember member, boolean translateAddress, boolean translatePort) { TransformationStep addressTranslation = translateAddress ? new AssignIpAddressFromPool( TransformationType.DEST_NAT, IpField.DESTINATION, ImmutableRangeSet.of(Range.singleton(member.getAddress()))) : null; TransformationStep portTranslation = translatePort ? new AssignPortFromPool( TransformationType.DEST_NAT, PortField.DESTINATION, member.getPort(), member.getPort()) : null; if (translateAddress && translatePort) { // pool return new ApplyAll(addressTranslation, portTranslation); } else if (translateAddress) { // pool return addressTranslation; } else if (translatePort) { // pool return portTranslation; } else { // ip-forward or just pool with weird options return Noop.NOOP_DEST_NAT; } }
Example #22
Source File: CrontabEntry.java From attic-aurora with Apache License 2.0 | 5 votes |
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 File: CrontabEntry.java From attic-aurora with Apache License 2.0 | 5 votes |
private RangeSet<Integer> parseHour() { RangeSet<Integer> hours = TreeRangeSet.create(); for (String component : getComponents(rawHour)) { hours.addAll(parseComponent(HOUR, component)); } return ImmutableRangeSet.copyOf(hours); }
Example #24
Source File: CumulusNcluConfigurationBuilder.java From batfish with Apache License 2.0 | 5 votes |
private static @Nonnull Set<String> toStrings(Glob_range_setContext ctx, long maxValue) { if (ctx.unnumbered != null) { return ImmutableSet.of(ctx.unnumbered.getText()); } String baseWord = ctx.base_word.getText(); if (ctx.first_interval_end == null && ctx.other_numeric_ranges == null) { return ImmutableSet.of(baseWord); } Matcher matcher = NUMBERED_WORD_PATTERN.matcher(baseWord); matcher.matches(); // parser+lexer guarantee match String prefix = matcher.group(1); long firstIntervalStart = Long.parseLong(matcher.group(2), 10); long firstIntervalEnd = ctx.first_interval_end != null ? Long.parseLong(ctx.first_interval_end.getText(), 10) : firstIntervalStart; checkArgument(firstIntervalStart <= maxValue && firstIntervalEnd <= maxValue); // attempt to add first interval ImmutableRangeSet.Builder<Long> builder = ImmutableRangeSet.builder(); try { // TODO have better parsing for globs: https://github.com/batfish/batfish/issues/4386 builder.add(Range.closed(firstIntervalStart, firstIntervalEnd)); } catch (IllegalArgumentException e) { return ImmutableSet.of(); } // All good, proceed to numeric ranges if (ctx.other_numeric_ranges != null) { // add other intervals RangeSet<Long> rangeSet = toRangeSet(ctx.other_numeric_ranges); checkUpperBound(rangeSet, maxValue); builder.addAll(rangeSet); } return builder.build().asRanges().stream() .flatMapToLong(r -> LongStream.rangeClosed(r.lowerEndpoint(), r.upperEndpoint())) .mapToObj(i -> String.format("%s%d", prefix, i)) .collect(ImmutableSet.toImmutableSet()); }
Example #25
Source File: AssignIpAddressFromPool.java From batfish with Apache License 2.0 | 5 votes |
@JsonCreator private static AssignIpAddressFromPool jsonCreator( @JsonProperty(PROP_TRANSFORMATION_TYPE) TransformationType type, @JsonProperty(PROP_IP_FIELD) IpField ipField, @JsonProperty(PROP_IP_RANGES) RangeSet<Ip> ipRanges) { checkNotNull(type, PROP_TRANSFORMATION_TYPE + " cannot be null"); checkNotNull(ipField, PROP_IP_FIELD + " cannot be null"); checkNotNull(ipRanges, PROP_IP_RANGES + " cannot be null"); return new AssignIpAddressFromPool(type, ipField, ImmutableRangeSet.copyOf(ipRanges)); }
Example #26
Source File: CrontabEntry.java From attic-aurora with Apache License 2.0 | 5 votes |
private RangeSet<Integer> parseDayOfWeek() { RangeSet<Integer> daysOfWeek = TreeRangeSet.create(); for (String component : getComponents(rawDayOfWeek)) { daysOfWeek.addAll(parseComponent(DAY_OF_WEEK, replaceNameAliases(component, DAY_NAMES))); } return ImmutableRangeSet.copyOf(daysOfWeek); }
Example #27
Source File: TestQuoteFilter.java From tac-kbp-eal with MIT License | 5 votes |
@Test public void testSerialization() throws IOException { final QuoteFilter reference = QuoteFilter.createFromBannedRegions( ImmutableMap.of( Symbol.from("dummy"), ImmutableRangeSet.<Integer>builder().add(Range.closed(4, 60)).add(Range.closed(67, 88)) .build(), Symbol.from("dummy2"), ImmutableRangeSet.of(Range.closed(0, 20)))); final ByteArraySink sink = ByteArraySink.create(); reference.saveTo(sink); final ByteSource source = ByteSource.wrap(sink.toByteArray()); final Object restored = QuoteFilter.loadFrom(source); assertEquals(reference, restored); }
Example #28
Source File: CrontabEntry.java From attic-aurora with Apache License 2.0 | 5 votes |
private RangeSet<Integer> parseMonth() { RangeSet<Integer> months = TreeRangeSet.create(); for (String component : getComponents(rawMonth)) { months.addAll(parseComponent(MONTH, replaceNameAliases(component, MONTH_NAMES))); } return ImmutableRangeSet.copyOf(months); }
Example #29
Source File: CrontabEntry.java From attic-aurora with Apache License 2.0 | 5 votes |
private RangeSet<Integer> parseDayOfMonth() { RangeSet<Integer> daysOfMonth = TreeRangeSet.create(); for (String component : getComponents(rawDayOfMonth)) { daysOfMonth.addAll(parseComponent(DAY_OF_MONTH, component)); } return ImmutableRangeSet.copyOf(daysOfMonth); }
Example #30
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); }