Example usage for com.google.common.collect Range upperBoundType

List of usage examples for com.google.common.collect Range upperBoundType

Introduction

In this page you can find the example usage for com.google.common.collect Range upperBoundType.

Prototype

public BoundType upperBoundType() 

Source Link

Document

Returns the type of this range's upper bound: BoundType#CLOSED if the range includes its upper endpoint, BoundType#OPEN if it does not.

Usage

From source file:com.wealdtech.jackson.modules.DateTimeRangeSerializer.java

@Override
public void serialize(final Range<DateTime> value, final JsonGenerator gen, final SerializerProvider provider)
        throws IOException {
    if (value != null) {
        final StringBuilder sb = new StringBuilder(64);
        if (value.hasLowerBound()) {
            if (value.lowerBoundType().equals(BoundType.CLOSED)) {
                sb.append('[');
            } else {
                sb.append('(');
            }/*w  ww . java 2  s .  c  o m*/
            sb.append(formatter.print(value.lowerEndpoint()));
        } else {
            sb.append('(');
            sb.append(NEGATIVE_INFINITY);
        }
        sb.append(',');

        if (value.hasUpperBound()) {
            sb.append(formatter.print(value.upperEndpoint()));
            if (value.upperBoundType().equals(BoundType.CLOSED)) {
                sb.append(']');
            } else {
                sb.append(')');
            }
        } else {
            sb.append(POSITIVE_INFINITY);
            sb.append(')');
        }

        gen.writeString(sb.toString());
    }
}

From source file:com.wealdtech.utils.RangeComparator.java

@Override
public int compare(Range<C> range1, Range<C> range2) {
    int result = ((Boolean) range1.hasLowerBound()).compareTo(range2.hasLowerBound());
    if (result == 0) {
        if (range1.hasLowerBound()) {
            result = range1.lowerEndpoint().compareTo(range2.lowerEndpoint());
            if (result == 0) {
                result = range1.lowerBoundType().compareTo(range2.lowerBoundType());
            }/* ww w . j a  va  2 s.  com*/
        }
    }

    if (result == 0) {
        result = ((Boolean) range1.hasUpperBound()).compareTo(range2.hasUpperBound());
        if (result == 0) {
            if (range1.hasUpperBound()) {
                result = range1.upperEndpoint().compareTo(range2.upperEndpoint());
                if (result == 0) {
                    result = range1.upperBoundType().compareTo(range2.upperBoundType());
                }
            }
        }
    }

    return result;
}

From source file:org.apache.kylin.common.util.RangeUtil.java

/**
 * remove from self the elements that exist in other
 * @return/*from  w w w .  j a  v a  2  s  . co  m*/
 */
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;

}

From source file:edu.mit.streamjit.impl.compiler2.CompositionAllocationStrategy.java

@Override
public void allocateGroup(ActorGroup group, Range<Integer> iterations, List<Core> cores, Configuration config) {
    if (group.isStateful()) {
        int minStatefulId = Integer.MAX_VALUE;
        for (Actor a : group.actors())
            if (a instanceof WorkerActor && ((WorkerActor) a).archetype().isStateful())
                minStatefulId = Math.min(minStatefulId, a.id());
        Configuration.SwitchParameter<Integer> param = config.getParameter("Group" + minStatefulId + "Core",
                Configuration.SwitchParameter.class, Integer.class);
        cores.get(param.getValue() % cores.size()).allocate(group, iterations);
        return;//w  w  w.  j  a v a 2  s . com
    }

    Configuration.CompositionParameter param = config.getParameter("Group" + group.id() + "Cores",
            Configuration.CompositionParameter.class);
    assert iterations.lowerBoundType() == BoundType.CLOSED && iterations.upperBoundType() == BoundType.OPEN;
    int totalAvailable = iterations.upperEndpoint() - iterations.lowerEndpoint();
    int[] allocations = new int[cores.size()];
    int totalAllocated = 0;
    for (int i = 0; i < param.getLength() && i < allocations.length; ++i) {
        int allocation = DoubleMath.roundToInt(param.getValue(i) * totalAvailable, RoundingMode.HALF_EVEN);
        allocations[i] = allocation;
        totalAllocated += allocation;
    }
    //If we allocated more than we have, remove from the cores with the least.
    //Need a loop here because we might not have enough on the least core.
    while (totalAllocated > totalAvailable) {
        int least = Ints.indexOf(allocations, Ints.max(allocations));
        for (int i = 0; i < allocations.length; ++i)
            if (allocations[i] > 0 && allocations[i] < allocations[least])
                least = i;
        int toRemove = Math.min(allocations[least], totalAllocated - totalAvailable);
        allocations[least] -= toRemove;
        totalAllocated -= toRemove;
    }
    //If we didn't allocate enough, allocate on the cores with the most.
    if (totalAllocated < totalAvailable) {
        int most = Ints.indexOf(allocations, Ints.min(allocations));
        for (int i = 0; i < allocations.length; ++i)
            if (allocations[i] > allocations[most])
                most = i;
        allocations[most] += totalAvailable - totalAllocated;
        totalAllocated += totalAvailable - totalAllocated;
    }
    assert totalAllocated == totalAvailable : totalAllocated + " " + totalAvailable;

    int lower = iterations.lowerEndpoint();
    for (int i = 0; i < allocations.length; ++i)
        if (allocations[i] > 0) {
            cores.get(i).allocate(group, Range.closedOpen(lower, lower + allocations[i]));
            lower += allocations[i];
        }
}

From source file:org.eclipse.fx.ui.controls.styledtext.internal.LineNode.java

protected Range<Integer> toGlobal(Range<Integer> range) {
    int lineOffset = this.lineHelper.getOffset(index);
    return Range.range(lineOffset + range.lowerEndpoint(), range.lowerBoundType(),
            lineOffset + range.upperEndpoint(), range.upperBoundType());
}

From source file:org.eclipse.fx.ui.controls.styledtext.internal.LineNode.java

protected Range<Integer> toLocal(Range<Integer> range) {
    int lineOffset = -this.lineHelper.getOffset(index);
    return Range.range(lineOffset + range.lowerEndpoint(), range.lowerBoundType(),
            lineOffset + range.upperEndpoint(), range.upperBoundType());
}

From source file:org.kiji.schema.impl.cassandra.CQLStatementCache.java

/**
 * Create a CQL statement for selecting the columns that make up the Entity ID from a Cassandra
 * Kiji Table./*from ww  w. j  a  va2 s.c o  m*/
 *
 * @param table The translated Cassandra table name.
 * @param tokenRange A range of tokens to scan.
 * @return a statement that will get the single column.
 */
public Statement createEntityIDScanStatement(final CassandraTableName table, final Range<Long> tokenRange) {

    // Retrieve the prepared statement from the cache

    // We can only use the 'DISTINCT' optimization if all entity ID components are part of the
    // partition key. CQL does not allow DISTINCT over non partition-key columns.
    final boolean useDistinct = mEntityIDClusteringColumns.isEmpty();

    final Optional<BoundType> lowerBound = tokenRange.hasLowerBound() ? Optional.of(tokenRange.lowerBoundType())
            : Optional.<BoundType>absent();

    final Optional<BoundType> upperBound = tokenRange.hasUpperBound() ? Optional.of(tokenRange.upperBoundType())
            : Optional.<BoundType>absent();

    final EntityIDScanStatementKey key = new EntityIDScanStatementKey(table, lowerBound, upperBound,
            useDistinct);
    final PreparedStatement statement = mCache.getUnchecked(key);

    // Bind the parameters to the prepared statement

    // slots are for the min/max token
    final List<Object> values = Lists.newArrayListWithCapacity(2);

    if (tokenRange.hasLowerBound()) {
        values.add(tokenRange.lowerEndpoint());
    }

    if (tokenRange.hasUpperBound()) {
        values.add(tokenRange.upperEndpoint());
    }

    return statement.bind(values.toArray()).setFetchSize(ENTITY_ID_BATCH_SIZE);
}

From source file:com.pingcap.tikv.predicates.ScanBuilder.java

private List<KeyRange> buildIndexScanKeyRange(TiTableInfo table, TiIndexInfo index,
        List<IndexRange> indexRanges) {
    requireNonNull(table, "Table cannot be null to encoding keyRange");
    requireNonNull(index, "Index cannot be null to encoding keyRange");
    requireNonNull(index, "indexRanges cannot be null to encoding keyRange");

    List<KeyRange> ranges = new ArrayList<>(indexRanges.size());

    for (IndexRange ir : indexRanges) {
        CodecDataOutput cdo = new CodecDataOutput();
        List<Object> values = ir.getAccessPoints();
        List<DataType> types = ir.getTypes();
        for (int i = 0; i < values.size(); i++) {
            Object v = values.get(i);
            DataType t = types.get(i);//  www .  ja v  a2s . co  m
            t.encode(cdo, DataType.EncodeType.KEY, v);
        }

        byte[] pointsData = cdo.toBytes();

        cdo.reset();
        Range r = ir.getRange();
        byte[] lPointKey;
        byte[] uPointKey;

        byte[] lKey;
        byte[] uKey;
        if (r == null) {
            lPointKey = pointsData;
            uPointKey = KeyUtils.prefixNext(lPointKey.clone());

            lKey = new byte[0];
            uKey = new byte[0];
        } else {
            lPointKey = pointsData;
            uPointKey = pointsData;

            DataType type = ir.getRangeType();
            if (!r.hasLowerBound()) {
                // -INF
                type.encodeMinValue(cdo);
                lKey = cdo.toBytes();
            } else {
                Object lb = r.lowerEndpoint();
                type.encode(cdo, DataType.EncodeType.KEY, lb);
                lKey = cdo.toBytes();
                if (r.lowerBoundType().equals(BoundType.OPEN)) {
                    lKey = KeyUtils.prefixNext(lKey);
                }
            }

            cdo.reset();
            if (!r.hasUpperBound()) {
                // INF
                type.encodeMaxValue(cdo);
                uKey = cdo.toBytes();
            } else {
                Object ub = r.upperEndpoint();
                type.encode(cdo, DataType.EncodeType.KEY, ub);
                uKey = cdo.toBytes();
                if (r.upperBoundType().equals(BoundType.CLOSED)) {
                    uKey = KeyUtils.prefixNext(lKey);
                }
            }

            cdo.reset();
        }
        TableCodec.writeIndexSeekKey(cdo, table.getId(), index.getId(), lPointKey, lKey);

        ByteString lbsKey = ByteString.copyFrom(cdo.toBytes());

        cdo.reset();
        TableCodec.writeIndexSeekKey(cdo, table.getId(), index.getId(), uPointKey, uKey);
        ByteString ubsKey = ByteString.copyFrom(cdo.toBytes());

        ranges.add(KeyRange.newBuilder().setStart(lbsKey).setEnd(ubsKey).build());
    }

    if (ranges.isEmpty()) {
        ranges.add(INDEX_FULL_RANGE);
    }
    return ranges;
}

From source file:com.pingcap.tikv.predicates.ScanBuilder.java

private List<KeyRange> buildTableScanKeyRange(TiTableInfo table, List<IndexRange> indexRanges) {
    requireNonNull(table, "Table cannot be null to encoding keyRange");
    requireNonNull(indexRanges, "indexRanges cannot be null to encoding keyRange");

    List<KeyRange> ranges = new ArrayList<>(indexRanges.size());
    for (IndexRange ir : indexRanges) {
        ByteString startKey;/*  w w w  . j a v  a 2  s .  c  om*/
        ByteString endKey;
        if (ir.hasAccessPoints()) {
            checkArgument(!ir.hasRange(), "Table scan must have one and only one access condition / point");

            Object v = ir.getAccessPoints().get(0);
            checkArgument(v instanceof Long, "Table scan key range must be long value");
            DataType type = ir.getTypes().get(0);
            checkArgument(type instanceof IntegerType, "Table scan key range must be long value");
            startKey = TableCodec.encodeRowKeyWithHandle(table.getId(), (long) v);
            endKey = ByteString.copyFrom(KeyUtils.prefixNext(startKey.toByteArray()));
        } else if (ir.hasRange()) {
            checkArgument(!ir.hasAccessPoints(),
                    "Table scan must have one and only one access condition / point");
            Range r = ir.getRange();
            DataType type = ir.getRangeType();
            checkArgument(type instanceof IntegerType, "Table scan key range must be long value");

            if (!r.hasLowerBound()) {
                // -INF
                // TODO: Domain and encoding should be further encapsulated
                startKey = TableCodec.encodeRowKeyWithHandle(table.getId(), Long.MIN_VALUE);
            } else {
                // Comparision with null should be filtered since it yields unknown always
                Object lb = r.lowerEndpoint();
                checkArgument(lb instanceof Long, "Table scan key range must be long value");
                long lVal = (long) lb;
                if (r.lowerBoundType().equals(BoundType.OPEN)) {
                    // TODO: Need push back?
                    if (lVal != Long.MAX_VALUE) {
                        lVal++;
                    }
                }
                startKey = TableCodec.encodeRowKeyWithHandle(table.getId(), lVal);
            }

            if (!r.hasUpperBound()) {
                // INF
                endKey = TableCodec.encodeRowKeyWithHandle(table.getId(), Long.MAX_VALUE);
            } else {
                Object ub = r.upperEndpoint();
                checkArgument(ub instanceof Long, "Table scan key range must be long value");
                long lVal = (long) ub;
                if (r.upperBoundType().equals(BoundType.CLOSED)) {
                    if (lVal != Long.MAX_VALUE) {
                        lVal++;
                    }
                }
                endKey = TableCodec.encodeRowKeyWithHandle(table.getId(), lVal);
            }
        } else {
            throw new TiClientInternalException("Empty access conditions");
        }

        ranges.add(KeyRange.newBuilder().setStart(startKey).setEnd(endKey).build());
    }

    if (ranges.isEmpty()) {
        ByteString startKey = TableCodec.encodeRowKeyWithHandle(table.getId(), Long.MIN_VALUE);
        ByteString endKey = TableCodec.encodeRowKeyWithHandle(table.getId(), Long.MAX_VALUE);
        ranges.add(KeyRange.newBuilder().setStart(startKey).setEnd(endKey).build());
    }

    return ranges;
}

From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.java

/**
 * Get the number of entries between a contiguous range of two positions
 *
 * @param range//from  w  w w.  j  a  v a  2  s. c o m
 *            the position range
 * @return the count of entries
 */
long getNumberOfEntries(Range<PositionImpl> range) {
    PositionImpl fromPosition = range.lowerEndpoint();
    boolean fromIncluded = range.lowerBoundType() == BoundType.CLOSED;
    PositionImpl toPosition = range.upperEndpoint();
    boolean toIncluded = range.upperBoundType() == BoundType.CLOSED;

    if (fromPosition.getLedgerId() == toPosition.getLedgerId()) {
        // If the 2 positions are in the same ledger
        long count = toPosition.getEntryId() - fromPosition.getEntryId() - 1;
        count += fromIncluded ? 1 : 0;
        count += toIncluded ? 1 : 0;
        return count;
    } else {
        long count = 0;
        // If the from & to are pointing to different ledgers, then we need to :
        // 1. Add the entries in the ledger pointed by toPosition
        count += toPosition.getEntryId();
        count += toIncluded ? 1 : 0;

        // 2. Add the entries in the ledger pointed by fromPosition
        LedgerInfo li = ledgers.get(fromPosition.getLedgerId());
        if (li != null) {
            count += li.getEntries() - (fromPosition.getEntryId() + 1);
            count += fromIncluded ? 1 : 0;
        }

        // 3. Add the whole ledgers entries in between
        for (LedgerInfo ls : ledgers.subMap(fromPosition.getLedgerId(), false, toPosition.getLedgerId(), false)
                .values()) {
            count += ls.getEntries();
        }

        return count;
    }
}