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

The following examples show how to use com.google.common.collect.BoundType. These examples are extracted from open source projects.
Example 1
Project: rubix   File: RemoteFetchProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void addToProcessQueue(String remotePath, Set<Range<Long>> closedOpenRanges, long fileSize, long lastModified)
{
  closedOpenRanges.stream()
          .forEach(range -> {
            checkState(range.lowerBoundType() == BoundType.CLOSED && range.upperBoundType() == BoundType.OPEN,
                    "Unexpected range type encountered lower=%s and upper=%s", range.lowerBoundType(), range.upperBoundType());
            long offset = range.lowerEndpoint();
            long rangeSpan = range.upperEndpoint() - range.lowerEndpoint();
            while (rangeSpan > 0) {
              int length = Math.toIntExact(Math.min(rangeSpan, Integer.MAX_VALUE));
              addToProcessQueue(remotePath, offset, length, fileSize, lastModified);
              rangeSpan -= length;
              offset += length;
            }
          });
}
 
Example 2
Project: jackson-datatypes-collections   File: RangeSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)
    throws JsonMappingException
{
    if (visitor != null) {
        JsonObjectFormatVisitor objectVisitor = visitor.expectObjectFormat(typeHint);
        if (objectVisitor != null) {
            if (_endpointSerializer != null) {
                JavaType endpointType = _rangeType.containedType(0);
                JavaType btType = visitor.getProvider().constructType(BoundType.class);
                // should probably keep track of `property`...
                JsonSerializer<?> btSer = visitor.getProvider()
                        .findContentValueSerializer(btType, null);
                objectVisitor.property(_fieldNames.lowerEndpoint, _endpointSerializer, endpointType);
                objectVisitor.property(_fieldNames.lowerBoundType, btSer, btType);
                objectVisitor.property(_fieldNames.upperEndpoint, _endpointSerializer, endpointType);
                objectVisitor.property(_fieldNames.upperBoundType, btSer, btType);
            }
        }
    }
}
 
Example 3
Project: tcl-regex-java   File: RuntimeColorMap.java    License: Apache License 2.0 6 votes vote down vote up
private void computeBmp(RangeMap<Integer, Short> fullMap) {
    for (Map.Entry<Range<Integer>, Short> me : fullMap.asMapOfRanges().entrySet()) {
        Range<Integer> range = me.getKey();
        int min = range.lowerEndpoint();
        if (range.lowerBoundType() == BoundType.OPEN) {
            min++;
        }
        if (min < Character.MAX_VALUE) {
            int rmax = range.upperEndpoint();
            if (range.upperBoundType() == BoundType.OPEN) {
                rmax--;
            }
            int max = Math.min(Character.MAX_VALUE, rmax);
            for (int x = min; x <= max; x++) {
                this.bmpMap[x] = me.getValue();
            }
        }
    }
}
 
Example 4
Project: pulsar   File: ConcurrentOpenLongPairRangeSet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds the specified range to this {@code RangeSet} (optional operation). That is, for equal range sets a and b,
 * the result of {@code a.add(range)} is that {@code a} will be the minimal range set for which both
 * {@code a.enclosesAll(b)} and {@code a.encloses(range)}.
 *
 * <p>Note that {@code range} will merge given {@code range} with any ranges in the range set that are
 * {@linkplain Range#isConnected(Range) connected} with it. Moreover, if {@code range} is empty/invalid, this is a
 * no-op.
 */
public void add(Range<LongPair> range) {
    LongPair lowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : LongPair.earliest;
    LongPair upperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : LongPair.latest;

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

    // #addOpenClosed doesn't create bitSet for lower-key because it avoids setting up values for non-exist items
    // into the key-ledger. so, create bitSet and initialize so, it can't be ignored at #addOpenClosed
    rangeBitSetMap.computeIfAbsent(lowerEndpoint.getKey(), (key) -> createNewBitSet())
            .set((int) lowerValueOpen + 1);
    this.addOpenClosed(lowerEndpoint.getKey(), lowerValueOpen, upperEndpoint.getKey(), upperValueClosed);
}
 
Example 5
Project: jackson-datatypes-collections   File: Range56Test.java    License: Apache License 2.0 6 votes vote down vote up
public void testSnakeCaseNamingStrategy() throws Exception
{
    String json = "{\"lower_endpoint\": 12, \"lower_bound_type\": \"CLOSED\", \"upper_endpoint\": 33, \"upper_bound_type\": \"CLOSED\"}";

    GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
    ObjectMapper mapper = JsonMapper.builder()
            .addModule(mod)
            .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
            .build();

    @SuppressWarnings("unchecked")
    Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);

    assertEquals(Integer.valueOf(12), r.lowerEndpoint());
    assertEquals(Integer.valueOf(33), r.upperEndpoint());

    assertEquals(BoundType.CLOSED, r.lowerBoundType());
    assertEquals(BoundType.CLOSED, r.upperBoundType());
}
 
Example 6
Project: jackson-datatypes-collections   File: TestRange.java    License: Apache License 2.0 6 votes vote down vote up
public void testDefaultBoundTypeOnlyUpperBoundTypeInformedWithClosedConfigured() throws Exception
{
    String json = "{\"lowerEndpoint\": 1, \"upperEndpoint\": 3, \"upperBoundType\": \"OPEN\"}";

    GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
    ObjectMapper mapper = JsonMapper.builder()
            .addModule(mod)
            .build();
    @SuppressWarnings("unchecked")
    Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);

    assertEquals(Integer.valueOf(1), r.lowerEndpoint());
    assertEquals(Integer.valueOf(3), r.upperEndpoint());
    assertEquals(BoundType.CLOSED, r.lowerBoundType());
    assertEquals(BoundType.OPEN, r.upperBoundType());
}
 
Example 7
Project: kite   File: Ranges.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static <C extends Comparable<C>> com.google.common.collect.Range<C> asGuavaRange(
    Range<C> range) {
  if (range.hasLowerBound()) {
    if (range.hasUpperBound()) {
      return com.google.common.collect.Ranges.range(
          range.lowerEndpoint(),
          range.isLowerBoundOpen() ? BoundType.OPEN : BoundType.CLOSED,
          range.upperEndpoint(),
          range.isUpperBoundOpen() ? BoundType.OPEN : BoundType.CLOSED);
    } else {
      return com.google.common.collect.Ranges.downTo(
          range.lowerEndpoint(),
          range.isLowerBoundOpen() ? BoundType.OPEN : BoundType.CLOSED);
    }
  } else if (range.hasUpperBound()) {
    return com.google.common.collect.Ranges.upTo(
        range.upperEndpoint(),
        range.isUpperBoundOpen() ? BoundType.OPEN : BoundType.CLOSED);
  } else {
    return com.google.common.collect.Ranges.all();
  }
}
 
Example 8
Project: jackson-datatypes-collections   File: TestRange.java    License: Apache License 2.0 6 votes vote down vote up
public void testDefaultBoundTypeBothBoundTypesOpenWithClosedConfigured() throws Exception
{
    String json = "{\"lowerEndpoint\": 1, \"lowerBoundType\": \"OPEN\", \"upperEndpoint\": 3, \"upperBoundType\": \"OPEN\"}";

    GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
    ObjectMapper mapper = JsonMapper.builder()
            .addModule(mod)
            .build();
    @SuppressWarnings("unchecked")
    Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);

    assertEquals(Integer.valueOf(1), r.lowerEndpoint());
    assertEquals(Integer.valueOf(3), r.upperEndpoint());

    assertEquals(BoundType.OPEN, r.lowerBoundType());
    assertEquals(BoundType.OPEN, r.upperBoundType());
}
 
Example 9
Project: jackson-datatypes-collections   File: TestRange.java    License: Apache License 2.0 6 votes vote down vote up
public void testDefaultBoundTypeBothBoundTypesClosedWithOpenConfigured() throws Exception
{
    String json = "{\"lowerEndpoint\": 12, \"lowerBoundType\": \"CLOSED\", \"upperEndpoint\": 33, \"upperBoundType\": \"CLOSED\"}";

    GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
    ObjectMapper mapper = JsonMapper.builder()
            .addModule(mod)
            .build();
    @SuppressWarnings("unchecked")
    Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);

    assertEquals(Integer.valueOf(12), r.lowerEndpoint());
    assertEquals(Integer.valueOf(33), r.upperEndpoint());

    assertEquals(BoundType.CLOSED, r.lowerBoundType());
    assertEquals(BoundType.CLOSED, r.upperBoundType());
}
 
Example 10
Project: jackson-datatypes-collections   File: TestRange.java    License: Apache License 2.0 6 votes vote down vote up
public void testSnakeCaseNamingStrategy() throws Exception
{
    String json = "{\"lower_endpoint\": 12, \"lower_bound_type\": \"CLOSED\", \"upper_endpoint\": 33, \"upper_bound_type\": \"CLOSED\"}";

    GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
    ObjectMapper mapper = JsonMapper.builder()
            .addModule(mod)
            .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
            .build();

    @SuppressWarnings("unchecked")
    Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);

    assertEquals(Integer.valueOf(12), r.lowerEndpoint());
    assertEquals(Integer.valueOf(33), r.upperEndpoint());

    assertEquals(BoundType.CLOSED, r.lowerBoundType());
    assertEquals(BoundType.CLOSED, r.upperBoundType());
}
 
Example 11
Project: activitystreams   File: Adapters.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public Range<?> deserialize(
  JsonElement json, 
  Type typeOfT,
  JsonDeserializationContext context) 
    throws JsonParseException {
  checkArgument(json.isJsonObject());
  try {
    JsonObject obj = json.getAsJsonObject();
    JsonObject upper = obj.getAsJsonObject("upper");
    JsonObject lower = obj.getAsJsonObject("lower");
    BoundType ubt = bt(upper.getAsJsonPrimitive("type"));
    BoundType lbt = bt(lower.getAsJsonPrimitive("type"));
    Object ub = des(upper.get("endpoint"),context);
    Object lb = des(lower.get("endpoint"),context);
    return Range.range((Comparable)lb, lbt, (Comparable)ub, ubt);
  } catch (Throwable t) {
    throw Throwables.propagate(t);
  }
}
 
Example 12
Project: pulsar   File: NamespaceBundleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEquals() throws Exception {
    NamespaceBundle bundle = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN));
    NamespaceBundle bundle2 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(0x20000000l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN));
    assertNotEquals(bundle2, bundle);

    NamespaceBundle bundle0 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN));
    assertEquals(bundle, bundle0);

    NamespaceBundle otherBundle = factory.getBundle(NamespaceName.get("pulsar/use/ns2"),
            Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN));
    assertNotEquals(bundle, otherBundle);
}
 
Example 13
Project: pulsar   File: NamespaceBundleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIncludes() throws Exception {
    TopicName topicName = TopicName.get("persistent://pulsar/use/ns1/topic-1");
    Long hashKey = factory.getLongHashCode(topicName.toString());
    Long upper = Math.max(hashKey + 1, NamespaceBundles.FULL_UPPER_BOUND);
    BoundType upperType = upper.equals(NamespaceBundles.FULL_UPPER_BOUND) ? BoundType.CLOSED : BoundType.OPEN;
    NamespaceBundle bundle = factory.getBundle(topicName.getNamespaceObject(),
            Range.range(hashKey / 2, BoundType.CLOSED, upper, upperType));
    assertTrue(bundle.includes(topicName));
    bundle = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(upper, BoundType.CLOSED, NamespaceBundles.FULL_UPPER_BOUND, BoundType.CLOSED));
    assertFalse(bundle.includes(topicName));

    NamespaceBundle otherBundle = factory.getBundle(NamespaceName.get("pulsar/use/ns2"),
            Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN));
    assertFalse(otherBundle.includes(topicName));
}
 
Example 14
Project: sharding-jdbc-1.5.1   File: HintManager.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private ShardingValue getShardingValue(final String logicTable, final String shardingColumn, final ShardingOperator operator, final Comparable<?>[] values) {
    Preconditions.checkArgument(null != values && values.length > 0);
    switch (operator) {
        case EQUAL:
            return new ShardingValue<Comparable<?>>(logicTable, shardingColumn, values[0]);
        case IN:
            return new ShardingValue(logicTable, shardingColumn, Arrays.asList(values));
        case BETWEEN:
            return new ShardingValue(logicTable, shardingColumn, Range.range(values[0], BoundType.CLOSED, values[1], BoundType.CLOSED));
        default:
            throw new UnsupportedOperationException(operator.getExpression());
    }
}
 
Example 15
Project: Bats   File: RexSimplify.java    License: Apache License 2.0 5 votes vote down vote up
private <C extends Comparable<C>> RexNode simplifyUsingPredicates(RexNode e, Class<C> clazz) {
    final Comparison comparison = Comparison.of(e);
    // Check for comparison with null values
    if (comparison == null || comparison.kind == SqlKind.NOT_EQUALS || comparison.literal.getValue() == null) {
        return e;
    }
    final C v0 = comparison.literal.getValueAs(clazz);
    final Range<C> range = range(comparison.kind, v0);
    final Range<C> range2 = residue(comparison.ref, range, predicates.pulledUpPredicates, clazz);
    if (range2 == null) {
        // Term is impossible to satisfy given these predicates
        return rexBuilder.makeLiteral(false);
    } else if (range2.equals(range)) {
        // no change
        return e;
    } else if (range2.equals(Range.all())) {
        // Range is always satisfied given these predicates; but nullability might
        // be problematic
        return simplify(rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, comparison.ref), RexUnknownAs.UNKNOWN);
    } else if (range2.lowerEndpoint().equals(range2.upperEndpoint())) {
        if (range2.lowerBoundType() == BoundType.OPEN || range2.upperBoundType() == BoundType.OPEN) {
            // range is a point, but does not include its endpoint, therefore is
            // effectively empty
            return rexBuilder.makeLiteral(false);
        }
        // range is now a point; it's worth simplifying
        return rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, comparison.ref, rexBuilder.makeLiteral(
                range2.lowerEndpoint(), comparison.literal.getType(), comparison.literal.getTypeName()));
    } else {
        // range has been reduced but it's not worth simplifying
        return e;
    }
}
 
Example 16
Project: PGM   File: KillStreakFilter.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected QueryResponse queryPlayer(PlayerQuery query, MatchPlayer player) {
  int streak =
      player.getMatch().needModule(KillRewardMatchModule.class).getKillStreak(player.getId());
  if (this.repeat && streak > 0) {
    int modulo =
        this.range.upperEndpoint() - (this.range.upperBoundType() == BoundType.CLOSED ? 0 : 1);
    streak = 1 + (streak - 1) % modulo;
  }
  return QueryResponse.fromBoolean(this.range.contains(streak));
}
 
Example 17
Project: tcl-regex-java   File: ColorMap.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * subrange - allocate new subcolors to this range of chars, fill in arcs.
 * The range will overlap existing ranges; even in the simplest case,
 * it will overlap the initial WHITE range. For each existing range that
 * it overlaps, allocate a new color, mark the range as mapping to that color,
 * and add an arc between the states for that color.
 */
void subrange(int from, int to, State lp, State rp) throws RegexException {
    /* Avoid one call to map.get() for each character in the range.
     * This map will usually contain one item, but in complex cases more.
     * For example, if we had [a-f][g-h] and then someone asked for [f-g], there
     * would be two. Each of these new ranges will get a new color via subcolor.
     */
    Map<Range<Integer>, Short> curColors = map.subRangeMap(Range.closed(from, to)).asMapOfRanges();
    /*
     * To avoid concurrent mod problems, we need to copy the ranges we are working from.
     */
    List<Range<Integer>> ranges = Lists.newArrayList(curColors.keySet());
    for (Range<Integer> rangeToProcess : ranges) {
        // bound management here irritating.
        int start = rangeToProcess.lowerEndpoint();
        if (rangeToProcess.lowerBoundType() == BoundType.OPEN) {
            start++;
        }
        int end = rangeToProcess.upperEndpoint();
        if (rangeToProcess.upperBoundType() == BoundType.CLOSED) {
            end++;
        }
        // allocate a new subcolor and account it owning the entire range.
        short color = subcolor(start, end - start);
        compiler.getNfa().newarc(Compiler.PLAIN, color, lp, rp);
    }
}
 
Example 18
Project: kylin-on-parquet-v2   File: RangeUtil.java    License: 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 19
Project: batfish   File: NumberSpace.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return least value.
 *
 * @throws NoSuchElementException if space is empty
 */
public final @Nonnull T least() {
  Range<T> span = _rangeset.span();
  T lowerEndpoint = span.lowerEndpoint();
  return span.lowerBoundType() == BoundType.CLOSED
      ? lowerEndpoint
      : discreteDomain().next(lowerEndpoint);
}
 
Example 20
Project: cava   File: DefaultWireConnection.java    License: Apache License 2.0 5 votes vote down vote up
private void initSupportedRange(List<Capability> capabilities) {
  int startRange = 17;
  for (Capability cap : capabilities) {
    for (SubProtocol sp : subprotocols.keySet()) {
      if (sp.supports(SubProtocolIdentifier.of(cap.name(), cap.version()))) {
        int numberOfMessageTypes = sp.versionRange(cap.version());
        subprotocolRangeMap
            .put(Range.range(startRange, BoundType.CLOSED, startRange + numberOfMessageTypes, BoundType.CLOSED), sp);
        startRange += numberOfMessageTypes + 1;
        break;
      }
    }
  }
}
 
Example 21
Project: java-monitoring-client-library   File: DistributionMetricSubject.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns an appropriate string representation of a metric value for use in error messages. */
@Override
protected String getMessageRepresentation(Distribution distribution) {
  StringBuilder sb = new StringBuilder("{");
  boolean first = true;
  for (Map.Entry<Range<Double>, Long> entry :
      distribution.intervalCounts().asMapOfRanges().entrySet()) {
    if (entry.getValue() != 0L) {
      if (first) {
        first = false;
      } else {
        sb.append(',');
      }
      if (entry.getKey().hasLowerBound()) {
        sb.append((entry.getKey().lowerBoundType() == BoundType.CLOSED) ? '[' : '(');
        sb.append(entry.getKey().lowerEndpoint());
      }
      sb.append("..");
      if (entry.getKey().hasUpperBound()) {
        sb.append(entry.getKey().upperEndpoint());
        sb.append((entry.getKey().upperBoundType() == BoundType.CLOSED) ? ']' : ')');
      }
      sb.append('=');
      sb.append(entry.getValue());
    }
  }
  sb.append('}');
  return sb.toString();
}
 
Example 22
Project: ProjectAres   File: MatchImpl.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void setPlayerLimits(Range<Integer> limits) {
    if(!playerLimits.equals(limits)) {
        checkArgument(limits.lowerBoundType() == BoundType.CLOSED);
        checkArgument(limits.upperBoundType() == BoundType.CLOSED);
        playerLimits = limits;
        callEvent(new MatchResizeEvent(this));
    }
}
 
Example 23
Project: ProjectAres   File: KillStreakFilter.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected boolean matches(IPlayerQuery query, MatchPlayer player) {
    final StatsUserFacet facet = player.getUserContext().facet(StatsUserFacet.class);
    int kills = persistent ? facet.teamKills() : facet.lifeKills();
    if(repeat && kills > 0) {
        int modulo = this.range.upperEndpoint() - (this.range.upperBoundType() == BoundType.CLOSED ? 0 : 1);
        kills = 1 + (kills - 1) % modulo;
    }
    return this.range.contains(kills);
}
 
Example 24
Project: luna   File: RandomUtils.java    License: 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 25
Project: hibernate-types   File: PostgreSQLGuavaRangeType.java    License: Apache License 2.0 5 votes vote down vote up
public String asString(Range range) {
    StringBuilder sb = new StringBuilder();

    sb.append(range.hasLowerBound() && range.lowerBoundType() == BoundType.CLOSED ? '[' : '(')
            .append(range.hasLowerBound() ? asString(range.lowerEndpoint()) : "")
            .append(",")
            .append(range.hasUpperBound() ? asString(range.upperEndpoint()) : "")
            .append(range.hasUpperBound() && range.upperBoundType() == BoundType.CLOSED ? ']' : ')');

    return sb.toString();
}
 
Example 26
Project: hibernate-types   File: PostgreSQLGuavaRangeType.java    License: Apache License 2.0 5 votes vote down vote up
public String asString(Range range) {
    StringBuilder sb = new StringBuilder();

    sb.append(range.hasLowerBound() && range.lowerBoundType() == BoundType.CLOSED ? '[' : '(')
            .append(range.hasLowerBound() ? range.lowerEndpoint().toString() : "")
            .append(",")
            .append(range.hasUpperBound() ? range.upperEndpoint().toString() : "")
            .append(range.hasUpperBound() && range.upperBoundType() == BoundType.CLOSED ? ']' : ')');

    return sb.toString();
}
 
Example 27
Project: hibernate-types   File: PostgreSQLGuavaRangeType.java    License: Apache License 2.0 5 votes vote down vote up
public String asString(Range range) {
    StringBuilder sb = new StringBuilder();

    sb.append(range.hasLowerBound() && range.lowerBoundType() == BoundType.CLOSED ? '[' : '(')
            .append(range.hasLowerBound() ? range.lowerEndpoint().toString() : "")
            .append(",")
            .append(range.hasUpperBound() ? range.upperEndpoint().toString() : "")
            .append(range.hasUpperBound() && range.upperBoundType() == BoundType.CLOSED ? ']' : ')');

    return sb.toString();
}
 
Example 28
Project: activitystreams   File: Parameter.java    License: Apache License 2.0 5 votes vote down vote up
public <O extends Comparable<? super O>>Range<O> bounds() {
  O mini = minInclusive();
  O mine = minExclusive();
  O maxi = maxInclusive();
  O maxe = maxExclusive();
  Ordering<O> ordering = Ordering.<O>natural();
  O min = ordering.nullsLast().min(mini,mine);
  O max = ordering.nullsFirst().max(maxi,maxe);
  BoundType lower = 
    min == null ? null :
    min == mini ? BoundType.CLOSED :
      BoundType.OPEN;
  BoundType upper = 
    max == null ? null : 
    max == maxi ? BoundType.CLOSED :
      BoundType.OPEN;
  if (lower == null && upper == null)
    return Range.<O>all();
  else if (lower != null && upper == null) 
    return lower == BoundType.CLOSED ? 
      Range.atLeast(min) : 
      Range.greaterThan(min);
  else if (lower == null && upper != null)
    return upper == BoundType.CLOSED ?
      Range.atMost(max) :
      Range.lessThan(max);
  else {
    return Range.range(min, lower, max, upper);
  }
}
 
Example 29
Project: jackson-datatypes-collections   File: RangeDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected RangeDeserializer(JavaType rangeType, JsonDeserializer<?> endpointDeser,
        BoundType defaultBoundType, RangeHelper.RangeProperties fieldNames)
{
    super(rangeType);
    _rangeType = rangeType;
    _endpointDeserializer = (JsonDeserializer<Object>) endpointDeser;
    _defaultBoundType = defaultBoundType;
    _fieldNames = fieldNames;
}
 
Example 30
Project: jackson-datatypes-collections   File: RangeDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
private BoundType deserializeBoundType(DeserializationContext context, JsonParser p) throws IOException
{
    expect(context, JsonToken.VALUE_STRING, p.currentToken());
    String name = p.getText();
    try {
        return BoundType.valueOf(name);
    } catch (IllegalArgumentException e) {
        return (BoundType) context.handleWeirdStringValue(BoundType.class, name,
                "not a valid BoundType name (should be one oF: %s)",
                asList(BoundType.values()));
    }
}
 
Example 31
Project: pulsar   File: NamespaceBundleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testToString() throws Exception {
    NamespaceBundle bundle0 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(0l, BoundType.CLOSED, 0x10000000L, BoundType.OPEN));
    assertEquals(bundle0.toString(), "pulsar/use/ns1/0x00000000_0x10000000");
    bundle0 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(0x10000000l, BoundType.CLOSED, NamespaceBundles.FULL_UPPER_BOUND, BoundType.CLOSED));
    assertEquals(bundle0.toString(), "pulsar/use/ns1/0x10000000_0xffffffff");
}
 
Example 32
Project: calcite   File: DruidDateTimeUtils.java    License: Apache License 2.0 5 votes vote down vote up
protected static List<Interval> toInterval(
    List<Range<Long>> ranges) {
  List<Interval> intervals = Lists.transform(ranges, range -> {
    if (!range.hasLowerBound() && !range.hasUpperBound()) {
      return DruidTable.DEFAULT_INTERVAL;
    }
    long start = range.hasLowerBound()
        ? range.lowerEndpoint().longValue()
        : DruidTable.DEFAULT_INTERVAL.getStartMillis();
    long end = range.hasUpperBound()
        ? range.upperEndpoint().longValue()
        : DruidTable.DEFAULT_INTERVAL.getEndMillis();
    if (range.hasLowerBound()
        && range.lowerBoundType() == BoundType.OPEN) {
      start++;
    }
    if (range.hasUpperBound()
        && range.upperBoundType() == BoundType.CLOSED) {
      end++;
    }
    return new Interval(start, end, ISOChronology.getInstanceUTC());
  });
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Converted time ranges " + ranges + " to interval " + intervals);
  }
  return intervals;
}
 
Example 33
Project: jackson-datatypes-collections   File: TestRange.java    License: Apache License 2.0 5 votes vote down vote up
public void testDefaultBoundTypeBothBoundTypesClosed() throws Exception
{
    String json = "{\"lowerEndpoint\": 1, \"lowerBoundType\": \"CLOSED\", \"upperEndpoint\": 3, \"upperBoundType\": \"CLOSED\"}";
    @SuppressWarnings("unchecked")
    Range<Integer> r = (Range<Integer>) MAPPER.readValue(json, Range.class);

    assertEquals(Integer.valueOf(1), r.lowerEndpoint());
    assertEquals(Integer.valueOf(3), r.upperEndpoint());

    assertEquals(BoundType.CLOSED, r.lowerBoundType());
    assertEquals(BoundType.CLOSED, r.upperBoundType());
}
 
Example 34
Project: ganttproject   File: DependencyGraph.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean refresh() {
  GPCalendarCalc calendar = myDstNode.myTask.getManager().getCalendar();
  TaskDependencyConstraint.Collision nextCollision = myDep.getConstraint().getCollision();
  Date acceptableStart = nextCollision.getAcceptableStart().getTime();
  isWeak = !nextCollision.isActive() && myDep.getHardness() == Hardness.RUBBER;
  switch (nextCollision.getVariation()) {
  case TaskDependencyConstraint.Collision.START_EARLIER_VARIATION:
    if (0 == (calendar.getDayMask(acceptableStart) & DayMask.WORKING)) {
      acceptableStart = calendar.findClosest(acceptableStart, myDstNode.myTask.getDuration().getTimeUnit(),
          GPCalendarCalc.MoveDirection.BACKWARD, GPCalendar.DayType.WORKING);
    }
    myStartRange = Range.upTo(acceptableStart, BoundType.CLOSED);
    break;
  case TaskDependencyConstraint.Collision.START_LATER_VARIATION:
    if (0 == (calendar.getDayMask(acceptableStart) & DayMask.WORKING)) {
      acceptableStart = calendar.findClosest(acceptableStart, myDstNode.myTask.getDuration().getTimeUnit(),
          GPCalendarCalc.MoveDirection.FORWARD, GPCalendar.DayType.WORKING);
    }
    myStartRange = Range.downTo(acceptableStart, BoundType.CLOSED);
    break;
  case TaskDependencyConstraint.Collision.NO_VARIATION:
    myStartRange = Range.singleton(acceptableStart);
    break;
  }
  myEndRange = Range.all();
  return true;
}
 
Example 35
Project: emodb   File: RestartingS3InputStream.java    License: Apache License 2.0 5 votes vote down vote up
public RestartingS3InputStream(AmazonS3 s3, String bucket, String key, @Nullable Range<Long> range) {
    _s3 = s3;
    _bucket = bucket;
    _key = key;

    S3Object s3Object;

    // Get the object synchronously so any immediate S3 errors, such as file not found, are thrown inline.
    if (range == null) {
        s3Object = _s3.getObject(new GetObjectRequest(_bucket, _key));
        _pos = 0;
        _length = s3Object.getObjectMetadata().getContentLength();
    } else {
        long start, end;

        if (range.hasLowerBound()) {
            start = range.lowerEndpoint() + (range.lowerBoundType() == BoundType.CLOSED ? 0 : 1);
        } else {
            start = 0;
        }

        if (range.hasUpperBound()) {
            end = range.upperEndpoint() - (range.upperBoundType() == BoundType.CLOSED ? 0 : 1);
        } else {
            end = Long.MAX_VALUE;
        }

        s3Object = _s3.getObject(new GetObjectRequest(_bucket, _key).withRange(start, end));

        _pos = start;
        // The S3 metadata's content length is the length of the data actually being returned by S3.
        // Since we effectively skipped the first "start" bytes we need to add them back to the total length
        // of data being read to make future calculations using _pos and _length consistent.
        _length = start + s3Object.getObjectMetadata().getContentLength();
    }

    _in = s3Object.getObjectContent();
}
 
Example 36
Project: shardingsphere   File: SafeRangeOperationUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertSafeIntersectionForInteger() {
    Range<Comparable<?>> range = Range.closed(10, 2000);
    Range<Comparable<?>> connectedRange = Range.closed(1500, 4000);
    Range<Comparable<?>> newRange = SafeRangeOperationUtils.safeIntersection(range, connectedRange);
    assertThat(newRange.lowerEndpoint(), is(1500));
    assertThat(newRange.lowerBoundType(), is(BoundType.CLOSED));
    assertThat(newRange.upperEndpoint(), is(2000));
    assertThat(newRange.upperBoundType(), is(BoundType.CLOSED));
}
 
Example 37
Project: shardingsphere   File: SafeRangeOperationUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertSafeIntersectionForBigInteger() {
    Range<Comparable<?>> range = Range.upTo(new BigInteger("131323233123211"), BoundType.CLOSED);
    Range<Comparable<?>> connectedRange = Range.downTo(35, BoundType.OPEN);
    Range<Comparable<?>> newRange = SafeRangeOperationUtils.safeIntersection(range, connectedRange);
    assertThat(newRange.lowerEndpoint(), is(new BigInteger("35")));
    assertThat(newRange.lowerBoundType(), is(BoundType.OPEN));
    assertThat(newRange.upperEndpoint(), is(new BigInteger("131323233123211")));
    assertThat(newRange.upperBoundType(), is(BoundType.CLOSED));
}
 
Example 38
Project: shardingsphere   File: SafeRangeOperationUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertSafeIntersectionForFloat() {
    Range<Comparable<?>> range = Range.closed(5.5F, 13.8F);
    Range<Comparable<?>> connectedRange = Range.closed(7.14F, 11.3F);
    Range<Comparable<?>> newRange = SafeRangeOperationUtils.safeIntersection(range, connectedRange);
    assertThat(newRange.lowerEndpoint(), is(7.14F));
    assertThat(newRange.lowerBoundType(), is(BoundType.CLOSED));
    assertThat(newRange.upperEndpoint(), is(11.3F));
    assertThat(newRange.upperBoundType(), is(BoundType.CLOSED));
}
 
Example 39
Project: shardingsphere   File: SafeRangeOperationUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertSafeIntersectionForDouble() {
    Range<Comparable<?>> range = Range.closed(1242.114, 31474836.12);
    Range<Comparable<?>> connectedRange = Range.downTo(567.34F, BoundType.OPEN);
    Range<Comparable<?>> newRange = SafeRangeOperationUtils.safeIntersection(range, connectedRange);
    assertThat(newRange.lowerEndpoint(), is(1242.114));
    assertThat(newRange.lowerBoundType(), is(BoundType.CLOSED));
    assertThat(newRange.upperEndpoint(), is(31474836.12));
    assertThat(newRange.upperBoundType(), is(BoundType.CLOSED));
}
 
Example 40
Project: shardingsphere   File: SafeRangeOperationUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertSafeIntersectionForBigDecimal() {
    Range<Comparable<?>> range = Range.upTo(new BigDecimal("2331.23211"), BoundType.CLOSED);
    Range<Comparable<?>> connectedRange = Range.open(135.13F, 45343.23F);
    Range<Comparable<?>> newRange = SafeRangeOperationUtils.safeIntersection(range, connectedRange);
    assertThat(newRange.lowerEndpoint(), is(new BigDecimal("135.13")));
    assertThat(newRange.lowerBoundType(), is(BoundType.OPEN));
    assertThat(newRange.upperEndpoint(), is(new BigDecimal("2331.23211")));
    assertThat(newRange.upperBoundType(), is(BoundType.CLOSED));
}