com.google.common.collect.BoundType Java Examples

The following examples show how to use com.google.common.collect.BoundType. 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: NamespaceBundleTest.java    From pulsar with 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 #2
Source File: RemoteFetchProcessor.java    From rubix with 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 #3
Source File: RangeSerializer.java    From jackson-datatypes-collections with 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 #4
Source File: TestRange.java    From jackson-datatypes-collections with 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 #5
Source File: TestRange.java    From jackson-datatypes-collections with 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 #6
Source File: RuntimeColorMap.java    From tcl-regex-java with 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 #7
Source File: TestRange.java    From jackson-datatypes-collections with 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 #8
Source File: Ranges.java    From kite with 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 #9
Source File: TestRange.java    From jackson-datatypes-collections with 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 #10
Source File: Range56Test.java    From jackson-datatypes-collections with 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
Source File: ConcurrentOpenLongPairRangeSet.java    From pulsar with 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 #12
Source File: Adapters.java    From activitystreams with 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 #13
Source File: NamespaceBundleTest.java    From pulsar with 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 #14
Source File: DependencyGraph.java    From ganttproject with 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 #15
Source File: ColorMap.java    From tcl-regex-java with 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 #16
Source File: NumberSpace.java    From batfish with 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 #17
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 #18
Source File: DefaultWireConnection.java    From cava with 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 #19
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with 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 #20
Source File: SafeRangeOperationUtilsTest.java    From shardingsphere with 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 #21
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with 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 #22
Source File: RestartingS3InputStream.java    From emodb with 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 #23
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with 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 #24
Source File: Parameter.java    From activitystreams with 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 #25
Source File: DruidDateTimeUtils.java    From calcite with 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 #26
Source File: RangeDeserializer.java    From jackson-datatypes-collections with 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 #27
Source File: RangeDeserializer.java    From jackson-datatypes-collections with 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 #28
Source File: TestRange.java    From jackson-datatypes-collections with 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 #29
Source File: HintManager.java    From sharding-jdbc-1.5.1 with 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 #30
Source File: NamespaceBundleTest.java    From pulsar with 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");
}