Java Code Examples for com.google.common.collect.Range#hasUpperBound()

The following examples show how to use com.google.common.collect.Range#hasUpperBound() . 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: QueryCardinalityUtil.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public Range<Long> visitAggregation(AggregationNode node, Void context)
{
    if (node.hasEmptyGroupingSet() && node.getGroupingSetCount() == 1) {
        // only single default aggregation which will produce exactly single row
        return Range.singleton(1L);
    }

    Range<Long> sourceCardinalityRange = node.getSource().accept(this, null);

    long lower;
    if (node.hasDefaultOutput() || sourceCardinalityRange.lowerEndpoint() > 0) {
        lower = 1;
    }
    else {
        lower = 0;
    }

    if (sourceCardinalityRange.hasUpperBound()) {
        long upper = Math.max(lower, sourceCardinalityRange.upperEndpoint());
        return Range.closed(lower, upper);
    }

    return Range.atLeast(lower);
}
 
Example 2
Source File: RangeSerializer.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
private void _writeContents(Range<?> value, JsonGenerator g, SerializerProvider provider)
    throws IOException
{
    if (value.hasLowerBound()) {
        if (_endpointSerializer != null) {
            g.writeFieldName(_fieldNames.lowerEndpoint);
            _endpointSerializer.serialize(value.lowerEndpoint(), g, provider);
        } else {
            provider.defaultSerializeField(_fieldNames.lowerEndpoint, value.lowerEndpoint(), g);
        }
        // 20-Mar-2016, tatu: Should not use default handling since it leads to
        //    [datatypes-collections#12] with default typing
        g.writeStringField(_fieldNames.lowerBoundType, value.lowerBoundType().name());
    }
    if (value.hasUpperBound()) {
        if (_endpointSerializer != null) {
            g.writeFieldName(_fieldNames.upperEndpoint);
            _endpointSerializer.serialize(value.upperEndpoint(), g, provider);
        } else {
            provider.defaultSerializeField(_fieldNames.upperEndpoint, value.upperEndpoint(), g);
        }
        // same as above; should always be just String so
        g.writeStringField(_fieldNames.upperBoundType, value.upperBoundType().name());
    }
}
 
Example 3
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 4
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
private static String determineRangeType(Range<?> range) {
    Object anyEndpoint = range.hasLowerBound() ? range.lowerEndpoint() :
                         range.hasUpperBound() ? range.upperEndpoint() : null;

    if (anyEndpoint == null) {
        throw new IllegalArgumentException("The range " + range + " doesn't have any upper or lower bound!");
    }

    Class<?> clazz = anyEndpoint.getClass();

    if (clazz.equals(Integer.class)) {
        return "int4range";
    } else if (clazz.equals(Long.class)) {
        return "int8range";
    } else if (clazz.equals(BigDecimal.class)) {
        return "numrange";
    }

    throw new IllegalStateException("The class [" + clazz.getName() + "] is not supported!");
}
 
Example 5
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
private static String determineRangeType(Range<?> range) {
    Object anyEndpoint = range.hasLowerBound() ? range.lowerEndpoint() :
                         range.hasUpperBound() ? range.upperEndpoint() : null;

    if (anyEndpoint == null) {
        throw new IllegalArgumentException("The range " + range + " doesn't have any upper or lower bound!");
    }

    Class<?> clazz = anyEndpoint.getClass();

    if (clazz.equals(Integer.class)) {
        return "int4range";
    } else if (clazz.equals(Long.class)) {
        return "int8range";
    } else if (clazz.equals(BigDecimal.class)) {
        return "numrange";
    }

    throw new IllegalStateException("The class [" + clazz.getName() + "] is not supported!");
}
 
Example 6
Source File: RangeMatcherBuilder.java    From grappa with Apache License 2.0 6 votes vote down vote up
private static Range<Integer> normalizeRange(final Range<Integer> range)
{
    Range<Integer> newRange = AT_LEAST_ZERO.intersection(range);

    if (newRange.isEmpty())
        throw new IllegalArgumentException("illegal range " + range
            + ": intersection with " + AT_LEAST_ZERO + " is empty");

    newRange = newRange.canonical(DiscreteDomain.integers());

    final int lowerBound = newRange.lowerEndpoint();

    return newRange.hasUpperBound()
        ? Range.closed(lowerBound, newRange.upperEndpoint() - 1)
        : Range.atLeast(lowerBound);
}
 
Example 7
Source File: RangeUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * for NavigableMap sorted by C, given a range of C, return the sub map whose key falls in the range
 */
public static <C extends Comparable<?>, V> NavigableMap<C, V> filter(NavigableMap<C, V> values, Range<C> filterRange) {
    if (filterRange == null || filterRange.isEmpty()) {
        return Maps.newTreeMap();
    } else if (filterRange.equals(Range.all())) {
        return values;
    }

    if (filterRange.hasUpperBound() && !filterRange.hasLowerBound()) {
        return values.headMap(filterRange.upperEndpoint(), upperBoundInclusive(filterRange));
    } else if (filterRange.hasLowerBound() && !filterRange.hasUpperBound()) {
        return values.tailMap(filterRange.lowerEndpoint(), lowerBoundInclusive(filterRange));
    } else {
        return values.subMap(filterRange.lowerEndpoint(), lowerBoundInclusive(filterRange), //
                filterRange.upperEndpoint(), upperBoundInclusive(filterRange));
    }
}
 
Example 8
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
private static String determineRangeType(Range<?> range) {
    Object anyEndpoint = range.hasLowerBound() ? range.lowerEndpoint() :
                         range.hasUpperBound() ? range.upperEndpoint() : null;

    if (anyEndpoint == null) {
        throw new IllegalArgumentException("The range " + range + " doesn't have any upper or lower bound!");
    }

    Class<?> clazz = anyEndpoint.getClass();

    if (clazz.equals(Integer.class)) {
        return "int4range";
    } else if (clazz.equals(Long.class)) {
        return "int8range";
    } else if (clazz.equals(BigDecimal.class)) {
        return "numrange";
    }

    throw new IllegalStateException("The class [" + clazz.getName() + "] is not supported!");
}
 
Example 9
Source File: FixedTimeZoneDateTimeRangeTransformerUnitTests.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "allZoneIdAndDateTimeRangeCombinations")
public void transformRangeShouldReturnCorrectRange(ZoneId zoneId, Range<OffsetDateTime> inputRange)
        throws Exception {

    FixedTimeZoneDateTimeRangeTransformer transformer = new FixedTimeZoneDateTimeRangeTransformer(zoneId);
    Range<OffsetDateTime> transformedRange = transformer.transformRange(inputRange);

    assertThat(transformedRange.hasLowerBound(), equalTo(inputRange.hasLowerBound()));

    if (transformedRange.hasLowerBound()) {
        // FIXME convert zone ID to offset
        //            assertThat(transformedRange.lowerEndpoint().getOffset(), equalTo(zoneId));
        assertThat(transformedRange.lowerEndpoint().toInstant(), equalTo(inputRange.lowerEndpoint().toInstant()));
    }

    assertThat(transformedRange.hasUpperBound(), equalTo(inputRange.hasUpperBound()));

    if (transformedRange.hasUpperBound()) {
        // FIXME convert zone ID to offset
        //            assertThat(transformedRange.upperEndpoint().getOffset(), equalTo(zoneId));
        assertThat(transformedRange.upperEndpoint().toInstant(), equalTo(inputRange.upperEndpoint().toInstant()));
    }
}
 
Example 10
Source File: QueryCardinalityUtil.java    From presto with Apache License 2.0 5 votes vote down vote up
private Range<Long> applyLimit(PlanNode source, long limit)
{
    Range<Long> sourceCardinalityRange = source.accept(this, null);
    if (sourceCardinalityRange.hasUpperBound()) {
        limit = min(sourceCardinalityRange.upperEndpoint(), limit);
    }
    long lower = min(limit, sourceCardinalityRange.lowerEndpoint());
    return Range.closed(lower, limit);
}
 
Example 11
Source File: SafeRangeOperationUtils.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Execute contains method by safe mode.
 *
 * @param range range
 * @param endpoint endpoint
 * @return whether the endpoint is included in the range
 */
public static boolean safeContains(final Range<Comparable<?>> range, final Comparable<?> endpoint) {
    try {
        return range.contains(endpoint);
    } catch (final ClassCastException ex) {
        Comparable<?> rangeUpperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null;
        Comparable<?> rangeLowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : null;
        Class<?> clazz = getTargetNumericType(Lists.newArrayList(rangeLowerEndpoint, rangeUpperEndpoint, endpoint));
        if (clazz == null) {
            throw ex;
        }
        Range<Comparable<?>> newRange = createTargetNumericTypeRange(range, clazz);
        return newRange.contains(parseNumberByClazz(endpoint.toString(), clazz));
    }
}
 
Example 12
Source File: FilterDefinitionParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@MethodParser("random")
public Filter parseRandom(Element el) throws InvalidXMLException {
    Node node = new Node(el);
    Range<Double> chance;
    try {
        chance = Range.closedOpen(0d, XMLUtils.parseNumber(node, Double.class));
    } catch(InvalidXMLException e) {
        chance = XMLUtils.parseNumericRange(node, Double.class);
    }

    Range<Double> valid = Range.closed(0d, 1d);
    if (valid.encloses(chance)) {
        return proto.isNoOlderThan(ProtoVersions.EVENT_QUERIES) ? new RandomFilter(chance)
                                                                : new LegacyRandomFilter(chance);
    } else {
        double lower = chance.hasLowerBound() ? chance.lowerEndpoint() : Double.NEGATIVE_INFINITY;
        double upper = chance.hasUpperBound() ? chance.upperEndpoint() : Double.POSITIVE_INFINITY;
        double invalid;
        if(!valid.contains(lower)) {
            invalid = lower;
        } else {
            invalid = upper;
        }

        throw new InvalidXMLException("chance value (" + invalid + ") is not between 0 and 1", el);
    }
}
 
Example 13
Source File: RangeUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static String formatTsRange(Range<Long> tsRange) {
    if (tsRange == null)
        return null;

    StringBuilder sb = new StringBuilder();
    if (tsRange.hasLowerBound()) {
        if (tsRange.lowerBoundType() == BoundType.CLOSED) {
            sb.append("[");
        } else {
            sb.append("(");
        }
        sb.append(DateFormat.formatToTimeStr(tsRange.lowerEndpoint()));
    } else {
        sb.append("(-∞");
    }

    sb.append("~");

    if (tsRange.hasUpperBound()) {
        sb.append(DateFormat.formatToTimeStr(tsRange.upperEndpoint()));
        if (tsRange.upperBoundType() == BoundType.CLOSED) {
            sb.append("]");
        } else {
            sb.append(")");
        }
    } else {
        sb.append("+∞)");
    }
    return sb.toString();
}
 
Example 14
Source File: RandomUtils.java    From luna with MIT License 5 votes vote down vote up
/**
 * Retrieves a random value from an {@code int} range.
 *
 * @param range The range.
 * @return The random value.
 */
public static int random(Range<Integer> range) {
    int low = range.hasLowerBound() ? range.lowerEndpoint() : Integer.MIN_VALUE;
    int high = range.hasUpperBound() ? range.upperEndpoint() : Integer.MAX_VALUE;
    if (range.upperBoundType() == BoundType.OPEN && range.lowerBoundType() == BoundType.CLOSED) {
        return inclusive(low - 1, high);
    } else if (range.upperBoundType() == BoundType.CLOSED && range.lowerBoundType() == BoundType.OPEN) {
        return inclusive(low, high - 1);
    } else if (range.upperBoundType() == BoundType.OPEN && range.lowerBoundType() == BoundType.OPEN) {
        return inclusive(low, high);
    } else if (range.upperBoundType() == BoundType.CLOSED && range.lowerBoundType() == BoundType.CLOSED) {
        return inclusive(low - 1, high - 1);
    }
    throw new Error("impossible");
}
 
Example 15
Source File: FilterDefinitionParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@MethodParser("kill-streak")
public KillStreakFilter parseKillStreak(Element el) throws InvalidXMLException {
    boolean repeat = XMLUtils.parseBoolean(el.getAttribute("repeat"), false);
    boolean persistent = XMLUtils.parseBoolean(el.getAttribute("persistent"), false);
    Integer count = XMLUtils.parseNumber(el.getAttribute("count"), Integer.class, (Integer) null);
    Integer min = XMLUtils.parseNumber(el.getAttribute("min"), Integer.class, (Integer) null);
    Integer max = XMLUtils.parseNumber(el.getAttribute("max"), Integer.class, (Integer) null);
    Range<Integer> range;

    if(count != null) {
        range = Range.singleton(count);
    } else if(min == null) {
        if(max == null) {
            throw new InvalidXMLException("kill-streak filter must have a count, min, or max", el);
        } else {
            range = Range.atMost(max);
        }
    } else {
        if(max == null) {
            range = Range.atLeast(min);
        } else {
            range = Range.closed(min, max);
        }
    }

    if(repeat && !range.hasUpperBound()) {
        throw new InvalidXMLException("repeating kill-streak filter must have a count or max", el);
    }

    return new KillStreakFilter(range, repeat, persistent);
}
 
Example 16
Source File: AbstractRangeShardingAlgorithm.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
private int getLastPartition(final Range<Long> valueRange) {
    return valueRange.hasUpperBound() ? getPartition(valueRange.upperEndpoint()) : partitionRange.size() - 1;
}
 
Example 17
Source File: RangeUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
/**
 * remove from self the elements that exist in other
 * @return
 */
public static <C extends Comparable<?>> List<Range<C>> remove(Range<C> self, Range<C> other) {

    // mimic the following logic in guava 18:
    //        RangeSet<C> rangeSet = TreeRangeSet.create();
    //        rangeSet.add(self);
    //        rangeSet.remove(other);
    //        return Lists.newArrayList(rangeSet.asRanges());

    if (other == null || !self.isConnected(other)) {
        return Collections.singletonList(self);
    }

    Range<C> share = self.intersection(other);
    if (share.isEmpty()) {
        return Collections.singletonList(self);
    }

    List<Range<C>> ret = Lists.newArrayList();

    //see left part
    if (!self.hasLowerBound()) {
        if (share.hasLowerBound()) {
            if (share.lowerBoundType() == BoundType.CLOSED) {
                ret.add(Range.lessThan(share.lowerEndpoint()));
            } else {
                ret.add(Range.atMost(share.lowerEndpoint()));
            }
        }
    } else {
        if (self.lowerEndpoint() != share.lowerEndpoint()) {
            if (self.lowerBoundType() == BoundType.CLOSED) {
                if (share.lowerBoundType() == BoundType.CLOSED) {
                    ret.add(Range.closedOpen(self.lowerEndpoint(), share.lowerEndpoint()));
                } else {
                    ret.add(Range.closed(self.lowerEndpoint(), share.lowerEndpoint()));
                }
            } else {
                if (share.lowerBoundType() == BoundType.CLOSED) {
                    ret.add(Range.open(self.lowerEndpoint(), share.lowerEndpoint()));
                } else {
                    ret.add(Range.openClosed(self.lowerEndpoint(), share.lowerEndpoint()));
                }
            }
        } else {
            if (self.lowerBoundType() == BoundType.CLOSED && share.lowerBoundType() == BoundType.OPEN) {
                ret.add(Range.closed(self.lowerEndpoint(), share.lowerEndpoint()));
            }
        }
    }

    //see right part 
    if (!self.hasUpperBound()) {
        if (share.hasUpperBound()) {
            if (share.upperBoundType() == BoundType.CLOSED) {
                ret.add(Range.greaterThan(share.upperEndpoint()));
            } else {
                ret.add(Range.atLeast(share.upperEndpoint()));
            }
        }
    } else {
        if (self.upperEndpoint() != share.upperEndpoint()) {
            if (self.upperBoundType() == BoundType.CLOSED) {
                if (share.upperBoundType() == BoundType.CLOSED) {
                    ret.add(Range.openClosed(share.upperEndpoint(), self.upperEndpoint()));
                } else {
                    ret.add(Range.closed(share.upperEndpoint(), self.upperEndpoint()));
                }
            } else {
                if (share.upperBoundType() == BoundType.CLOSED) {
                    ret.add(Range.open(share.upperEndpoint(), self.upperEndpoint()));
                } else {
                    ret.add(Range.closedOpen(share.upperEndpoint(), self.upperEndpoint()));
                }
            }
        } else {
            if (self.upperBoundType() == BoundType.CLOSED && share.upperBoundType() == BoundType.OPEN) {
                ret.add(Range.closed(self.upperEndpoint(), share.upperEndpoint()));
            }
        }
    }

    return ret;

}
 
Example 18
Source File: RangeUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
public static <C extends Comparable<?>> boolean upperBoundInclusive(Range<C> range) {
    if (!range.hasUpperBound()) {
        throw new IllegalArgumentException(("This range does not have upper bound" + range));
    }
    return range.upperBoundType() == BoundType.CLOSED;
}
 
Example 19
Source File: ExternalSubCreator.java    From SubServers-2 with Apache License 2.0 4 votes vote down vote up
@Override
public void setPortRange(Range<Integer> value) {
    if (!value.hasLowerBound() || !value.hasUpperBound()) throw new IllegalArgumentException("Port range is not bound");
    ports = value;
}
 
Example 20
Source File: ConcurrentOpenLongPairRangeSet.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public void remove(Range<LongPair> range) {
    LongPair lowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : LongPair.earliest;
    LongPair upperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : LongPair.latest;

    long lower = (range.hasLowerBound() && range.lowerBoundType().equals(BoundType.CLOSED))
            ? getSafeEntry(lowerEndpoint)
            : getSafeEntry(lowerEndpoint) + 1;
    long upper = (range.hasUpperBound() && range.upperBoundType().equals(BoundType.CLOSED))
            ? getSafeEntry(upperEndpoint)
            : getSafeEntry(upperEndpoint) - 1;

    // if lower-bound is not set then remove all the keys less than given upper-bound range
    if (lowerEndpoint.equals(LongPair.earliest)) {
        // remove all keys with
        rangeBitSetMap.forEach((key, set) -> {
            if (key < upperEndpoint.getKey()) {
                rangeBitSetMap.remove(key);
            }
        });
    }

    // if upper-bound is not set then remove all the keys greater than given lower-bound range
    if (upperEndpoint.equals(LongPair.latest)) {
        // remove all keys with
        rangeBitSetMap.forEach((key, set) -> {
            if (key > lowerEndpoint.getKey()) {
                rangeBitSetMap.remove(key);
            }
        });
    }

    // remove all the keys between two endpoint keys
    rangeBitSetMap.forEach((key, set) -> {
        if (lowerEndpoint.getKey() == upperEndpoint.getKey()) {
            set.clear((int) lower, (int) upper + 1);
        } else {
            // eg: remove-range: [(3,5) - (5,5)] -> Delete all items from 3,6->3,N,4.*,5,0->5,5
            if (key == lowerEndpoint.getKey()) {
                // remove all entries from given position to last position
                set.clear((int) lower, set.previousSetBit(set.size()));
            } else if (key == upperEndpoint.getKey()) {
                // remove all entries from 0 to given position
                set.clear(0, (int) upper + 1);
            } else if (key > lowerEndpoint.getKey() && key < upperEndpoint.getKey()) {
                rangeBitSetMap.remove(key);
            }
        }
        // remove bit-set if set is empty
        if (set.isEmpty()) {
            rangeBitSetMap.remove(key);
        }
    });

    updatedAfterCachedForSize = true;
    updatedAfterCachedForToString = true;
}