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

The following are top voted examples for showing how to use com.google.common.collect.BoundType. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-pulsar   File: PulsarWebResource.java   View source code 6 votes vote down vote up
protected NamespaceBundle validateNamespaceBundleRange(NamespaceName fqnn, BundlesData bundles,
        String bundleRange) {
    try {
        checkArgument(bundleRange.contains("_"), "Invalid bundle range");
        String[] boundaries = bundleRange.split("_");
        Long lowerEndpoint = Long.decode(boundaries[0]);
        Long upperEndpoint = Long.decode(boundaries[1]);
        Range<Long> hashRange = Range.range(lowerEndpoint, BoundType.CLOSED, upperEndpoint,
                (upperEndpoint.equals(NamespaceBundles.FULL_UPPER_BOUND)) ? BoundType.CLOSED : BoundType.OPEN);
        NamespaceBundle nsBundle = pulsar().getNamespaceService().getNamespaceBundleFactory().getBundle(fqnn,
                hashRange);
        NamespaceBundles nsBundles = pulsar().getNamespaceService().getNamespaceBundleFactory().getBundles(fqnn,
                bundles);
        nsBundles.validateBundle(nsBundle);
        return nsBundle;
    } catch (Exception e) {
        log.error("[{}] Failed to validate namespace bundle {}/{}", clientAppId(), fqnn.toString(), bundleRange, e);
        throw new RestException(e);
    }
}
 
Example 2
Project: incubator-pulsar   File: NamespaceBundleTest.java   View source code 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));
    assertTrue(!bundle.equals(bundle2));

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

    NamespaceBundle otherBundle = factory.getBundle(NamespaceName.get("pulsar/use/ns2"),
            Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN));
    assertTrue(!otherBundle.equals(bundle));
}
 
Example 3
Project: incubator-pulsar   File: NamespaceBundleTest.java   View source code 6 votes vote down vote up
@Test
public void testIncludes() throws Exception {
    DestinationName dn = DestinationName.get("persistent://pulsar/use/ns1/topic-1");
    Long hashKey = factory.getLongHashCode(dn.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(dn.getNamespaceObject(),
            Range.range(hashKey / 2, BoundType.CLOSED, upper, upperType));
    assertTrue(bundle.includes(dn));
    bundle = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(upper, BoundType.CLOSED, NamespaceBundles.FULL_UPPER_BOUND, BoundType.CLOSED));
    assertTrue(!bundle.includes(dn));

    NamespaceBundle otherBundle = factory.getBundle(NamespaceName.get("pulsar/use/ns2"),
            Range.range(0l, BoundType.CLOSED, 0x40000000L, BoundType.OPEN));
    assertTrue(!otherBundle.includes(dn));
}
 
Example 4
Project: r01fb   File: LuceneSearchQuery.java   View source code 6 votes vote down vote up
private static <N extends Number> Query _numberEqualsQuery(final IndexDocumentFieldID fieldId,
														   final N number,
														   final Class<N> numberType) {
	Query outQry = null;
	if (numberType.equals(Integer.class)) {
		outQry = _numberInRangeQuery(fieldId,
									 _createRange((Integer)number,BoundType.CLOSED,(Integer)number,BoundType.CLOSED),
									 Integer.class);
	} else if (numberType.equals(Long.class)) {
		outQry = _numberInRangeQuery(fieldId,
									 _createRange((Long)number,BoundType.CLOSED,(Long)number,BoundType.CLOSED),
									 Long.class);
	} else if (numberType.equals(Double.class)) {
		outQry = _numberInRangeQuery(fieldId,
									 _createRange((Double)number,BoundType.CLOSED,(Double)number,BoundType.CLOSED),
									 Double.class);
	} else if (numberType.equals(Long.class)) {
		outQry = _numberInRangeQuery(fieldId,
									 _createRange((Float)number,BoundType.CLOSED,(Float)number,BoundType.CLOSED),
									 Float.class);
	} else {
		throw new IllegalArgumentException();
	}
	return outQry;
}
 
Example 5
Project: codemining-treelm   File: AbstractTSGSampler.java   View source code 6 votes vote down vote up
/**
 * Print statistics on stdout.
 */
protected void printStats() {
	final SortedMultiset<Integer> sizeDistribution = sampleGrammar
			.computeGrammarTreeSizeStats();
	System.out.println("Size Stats: 1-5:"
			+ sizeDistribution.subMultiset(0, BoundType.CLOSED, 5,
					BoundType.CLOSED).size()
					+ " 6-15:"
					+ sizeDistribution.subMultiset(6, BoundType.CLOSED, 15,
							BoundType.CLOSED).size()
							+ " 16-30:"
							+ sizeDistribution.subMultiset(16, BoundType.CLOSED, 30,
									BoundType.CLOSED).size()
									+ " >30:"
									+ sizeDistribution.subMultiset(31, BoundType.CLOSED,
											Integer.MAX_VALUE, BoundType.CLOSED).size());

	int sumOfSizes = 0;
	for (final com.google.common.collect.Multiset.Entry<Integer> sizeEntry : sizeDistribution
			.entrySet()) {
		sumOfSizes += sizeEntry.getCount() * sizeEntry.getElement();
	}

	final double avgSize = (((double) sumOfSizes) / sizeDistribution.size());
	System.out.println("Avg Tree Size: " + String.format("%.2f", avgSize));
}
 
Example 6
Project: codemining-treelm   File: SuggestIdiomsGivenImports.java   View source code 6 votes vote down vote up
/**
 * Prune the list to the given threshold.
 */
private List<Pair<SortedMultiset<Double>, SortedMultiset<Double>>> pruneToThreshold(
		final double threshold) {
	final List<Pair<SortedMultiset<Double>, SortedMultiset<Double>>> filtered = Lists
			.newArrayList();

	for (final Pair<SortedMultiset<Double>, SortedMultiset<Double>> suggestion : suggestionPrecision) {
		final SortedMultiset<Double> allFilteredSuggestions = suggestion.first
				.tailMultiset(threshold, BoundType.CLOSED);
		final SortedMultiset<Double> correctFilteredSuggestions = suggestion.second
				.tailMultiset(threshold, BoundType.CLOSED);
		final Pair<SortedMultiset<Double>, SortedMultiset<Double>> filteredPair = Pair
				.create(allFilteredSuggestions,
						correctFilteredSuggestions);
		filtered.add(filteredPair);
	}

	return filtered;
}
 
Example 7
Project: activitystreams   File: Adapters.java   View source code 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 8
Project: jiplib   File: IPAddresses.java   View source code 6 votes vote down vote up
static Range<IPAddress> canonical(final Range<IPAddress> range,
    final LongDiscreteDomain<IPAddress> domain) {
  if (range.isEmpty()) {
    return null;
  }
  final boolean l = range.lowerBoundType() == BoundType.OPEN;
  final boolean u = range.upperBoundType() == BoundType.OPEN;
  final IPAddress s = range.lowerEndpoint();
  final IPAddress e = range.upperEndpoint();
  if (l && u) {
    Range.closed(domain.next(s), domain.previous(e));
  } else if (l) {
    return Range.closed(domain.next(s), e);
  } else if (u) {
    return Range.closed(s, domain.previous(e));
  }
  return range;
}
 
Example 9
Project: tcl-regex-java   File: RuntimeColorMap.java   View source code 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 10
Project: variation-cytoscape3-app   File: Ranges.java   View source code 6 votes vote down vote up
/**
 * Return true if the specified range is strictly less than the specified value.
 *
 * @param <C> range endpoint type
 * @param range range, must not be null
 * @param value value, must not be null
 * @return true if the specified range is strictly less than the specified value
 */
public static <C extends Comparable> boolean isLessThan(final Range<C> range, final C value)
{
    checkNotNull(range);
    checkNotNull(value);

    if (!range.hasUpperBound())
    {
        return false;
    }
    if (range.upperBoundType() == BoundType.OPEN && range.upperEndpoint().equals(value))
    {
        return true;
    }
    return range.upperEndpoint().compareTo(value) < 0;
}
 
Example 11
Project: java-monitoring-client-library   File: DistributionMetricSubject.java   View source code 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 12
Project: guava-mock   File: MultisetNavigationTester.java   View source code 5 votes vote down vote up
@CollectionSize.Require(ZERO)
public void testEmptyMultisetNearby() {
  for (BoundType type : BoundType.values()) {
    assertNull(sortedMultiset.headMultiset(e0(), type).lastEntry());
    assertNull(sortedMultiset.tailMultiset(e0(), type).firstEntry());
  }
}
 
Example 13
Project: ProjectAres   File: MatchImpl.java   View source code 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 14
Project: ProjectAres   File: KillStreakFilter.java   View source code 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 15
Project: ProjectAres   File: Ranges.java   View source code 5 votes vote down vote up
/**
 * Return an english phrase describing the given {@link Range} e.g.
 *
 *     Range.all()                      -> "unbounded"
 *     Range.singleton(3)               -> "3"
 *     Range.atLeast(3)                 -> "at least 3"
 *     Range.closedOpen(3, 7)           -> "at least 3 and less than 7"
 *     Range.closed(3, 7)               -> "between 3 and 7"
 */
public static String describe(Range<?> range) {
    if(range.hasLowerBound() && range.hasUpperBound() && range.lowerBoundType() == BoundType.CLOSED && range.upperBoundType() == BoundType.CLOSED) {
        if(range.lowerEndpoint().equals(range.upperEndpoint())) {
            // singleton
            return range.lowerEndpoint().toString();
        } else {
            // closed-closed
            return "between " + range.lowerEndpoint() + " and " + range.upperEndpoint();
        }
    }

    final List<String> parts = new ArrayList<>(2);

    if(range.hasLowerBound()) {
        parts.add((range.lowerBoundType() == BoundType.CLOSED ? "at least " : "more than ") + range.lowerEndpoint());
    }

    if(range.hasUpperBound()) {
        parts.add((range.upperBoundType() == BoundType.CLOSED ? "at most " : "less than ") + range.upperEndpoint());
    }

    switch(parts.size()) {
        case 0: return "unbounded";
        case 1: return parts.get(0);
        default: return parts.get(0) + " and " + parts.get(1);
    }
}
 
Example 16
Project: googles-monorepo-demo   File: MultisetNavigationTester.java   View source code 5 votes vote down vote up
@CollectionSize.Require(ZERO)
public void testEmptyMultisetNearby() {
  for (BoundType type : BoundType.values()) {
    assertNull(sortedMultiset.headMultiset(e0(), type).lastEntry());
    assertNull(sortedMultiset.tailMultiset(e0(), type).firstEntry());
  }
}
 
Example 17
Project: oma-riista-web   File: NumberGenerator.java   View source code 5 votes vote down vote up
default int nextInt(final Range<Integer> range) {
    final int upperEndPoint = range.hasUpperBound()
            ? range.upperBoundType() == BoundType.CLOSED ? range.upperEndpoint() : range.upperEndpoint() - 1
            : Integer.MAX_VALUE;

    final int lowerEndPoint = range.hasLowerBound()
            ? range.lowerBoundType() == BoundType.CLOSED ? range.lowerEndpoint() : range.lowerEndpoint() + 1
            : Integer.MIN_VALUE;

    return nextIntBetween(lowerEndPoint, upperEndPoint);
}
 
Example 18
Project: incubator-pulsar   File: ServiceUnitZkUtils.java   View source code 5 votes vote down vote up
private static Range<Long> getHashRange(String rangePathPart) {
    String[] endPoints = rangePathPart.split("_");
    checkArgument(endPoints.length == 2, "Malformed bundle hash range path part:" + rangePathPart);
    Long startLong = Long.decode(endPoints[0]);
    Long endLong = Long.decode(endPoints[1]);
    BoundType endType = (endPoints[1].equals(LAST_BOUNDARY)) ? BoundType.CLOSED : BoundType.OPEN;
    return Range.range(startLong, BoundType.CLOSED, endLong, endType);
}
 
Example 19
Project: incubator-pulsar   File: NamespaceBundle.java   View source code 5 votes vote down vote up
public NamespaceBundle(NamespaceName nsname, Range<Long> keyRange, NamespaceBundleFactory factory) {
    this.nsname = checkNotNull(nsname);
    this.keyRange = checkNotNull(keyRange);
    checkArgument(this.keyRange.lowerBoundType().equals(BoundType.CLOSED),
            "Invalid hash range. Lower Endpoint has to be inclusive");
    checkArgument(
            (this.keyRange.upperEndpoint().equals(NamespaceBundles.FULL_UPPER_BOUND)
                    && this.keyRange.upperBoundType().equals(BoundType.CLOSED))
                    || (!this.keyRange.upperEndpoint().equals(NamespaceBundles.FULL_UPPER_BOUND)
                            && this.keyRange.upperBoundType().equals(BoundType.OPEN)),
            "Invalid hash range. Upper Endpoint should be exclusive unless it is 0xffffffff");
    checkArgument(!this.keyRange.isEmpty(), "Cannot create bundle object for an empty key range");
    this.factory = checkNotNull(factory);
}
 
Example 20
Project: incubator-pulsar   File: NamespaceBundles.java   View source code 5 votes vote down vote up
public NamespaceBundles(NamespaceName nsname, long[] partitions, NamespaceBundleFactory factory) {
    // check input arguments
    this.nsname = checkNotNull(nsname);
    this.factory = checkNotNull(factory);
    checkArgument(partitions.length > 0, "Can't create bundles w/o partition boundaries");

    // calculate bundles based on partition boundaries
    this.bundles = Lists.newArrayList();
    fullBundle = new NamespaceBundle(nsname,
            Range.range(FULL_LOWER_BOUND, BoundType.CLOSED, FULL_UPPER_BOUND, BoundType.CLOSED), factory);

    if (partitions.length > 0) {
        if (partitions.length == 1) {
            throw new IllegalArgumentException("Need to specify at least 2 boundaries");
        }

        this.partitions = partitions;
        long lowerBound = partitions[0];
        for (int i = 1; i < partitions.length; i++) {
            long upperBound = partitions[i];
            checkArgument(upperBound >= lowerBound);
            Range<Long> newRange = null;
            if (i != partitions.length - 1) {
                newRange = Range.range(lowerBound, BoundType.CLOSED, upperBound, BoundType.OPEN);
            } else {
                // last one has a closed right end
                newRange = Range.range(lowerBound, BoundType.CLOSED, upperBound, BoundType.CLOSED);
            }
            bundles.add(new NamespaceBundle(nsname, newRange, factory));
            lowerBound = upperBound;
        }
    } else {
        this.partitions = new long[] { 0l };
        bundles.add(fullBundle);
    }
}
 
Example 21
Project: incubator-pulsar   File: NamespaceBundleFactory.java   View source code 5 votes vote down vote up
public NamespaceBundle getBundle(String namespace, String bundleRange) {
    checkArgument(bundleRange.contains("_"), "Invalid bundle range");
    String[] boundaries = bundleRange.split("_");
    Long lowerEndpoint = Long.decode(boundaries[0]);
    Long upperEndpoint = Long.decode(boundaries[1]);
    Range<Long> hashRange = Range.range(lowerEndpoint, BoundType.CLOSED, upperEndpoint,
            (upperEndpoint.equals(NamespaceBundles.FULL_UPPER_BOUND)) ? BoundType.CLOSED : BoundType.OPEN);
    return getBundle(NamespaceName.get(namespace), hashRange);
}
 
Example 22
Project: incubator-pulsar   File: LoadBalancerTestingUtils.java   View source code 5 votes vote down vote up
public static NamespaceBundle[] makeBundles(final NamespaceBundleFactory nsFactory, final String property,
        final String cluster, final String namespace, final int numBundles) {
    final NamespaceBundle[] result = new NamespaceBundle[numBundles];
    final NamespaceName namespaceName = NamespaceName.get(property, cluster, namespace);
    for (int i = 0; i < numBundles - 1; ++i) {
        final long lower = NamespaceBundles.FULL_UPPER_BOUND * i / numBundles;
        final long upper = NamespaceBundles.FULL_UPPER_BOUND * (i + 1) / numBundles;
        result[i] = nsFactory.getBundle(namespaceName, Range.range(lower, BoundType.CLOSED, upper, BoundType.OPEN));
    }
    result[numBundles - 1] = nsFactory.getBundle(namespaceName,
            Range.range(NamespaceBundles.FULL_UPPER_BOUND * (numBundles - 1) / numBundles, BoundType.CLOSED,
                    NamespaceBundles.FULL_UPPER_BOUND, BoundType.CLOSED));
    return result;
}
 
Example 23
Project: incubator-pulsar   File: NamespaceBundleTest.java   View source code 5 votes vote down vote up
@Test
public void testGetBundle() throws Exception {
    NamespaceBundle bundle = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(0L, BoundType.CLOSED, 0xffffffffL, BoundType.CLOSED));
    assertNotNull(bundle);
    NamespaceBundle bundle2 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(0L, BoundType.CLOSED, 0xffffffffL, BoundType.CLOSED));
    // Don't call equals and make sure those two are the same instance
    assertEquals(bundle, bundle2);

}
 
Example 24
Project: incubator-pulsar   File: NamespaceBundleTest.java   View source code 5 votes vote down vote up
@Test
public void testCompareTo() 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));
    try {
        bundle.compareTo(bundle2);
        fail("Should have failed due to overlap ranges");
    } catch (IllegalArgumentException iae) {
        // OK, expected
    }

    NamespaceBundle bundle0 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(0l, BoundType.CLOSED, 0x10000000L, BoundType.OPEN));
    assertTrue(bundle0.compareTo(bundle2) < 0);
    assertTrue(bundle2.compareTo(bundle0) > 0);
    NamespaceBundle bundle1 = factory.getBundle(NamespaceName.get("pulsar/use/ns1"),
            Range.range(0l, BoundType.CLOSED, 0x20000000L, BoundType.OPEN));
    assertTrue(bundle1.compareTo(bundle2) < 0);

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

    NamespaceBundle otherBundle = factory.getBundle(NamespaceName.get("pulsar/use/ns2"),
            Range.range(0x10000000l, BoundType.CLOSED, 0x30000000L, BoundType.OPEN));
    assertTrue(otherBundle.compareTo(bundle0) > 0);
}
 
Example 25
Project: incubator-pulsar   File: NamespaceBundleTest.java   View source code 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 26
Project: emodb   File: RestartingS3InputStream.java   View source code 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 27
Project: guava-libraries   File: MultisetNavigationTester.java   View source code 5 votes vote down vote up
@CollectionSize.Require(ZERO)
public void testEmptyMultisetNearby() {
  for (BoundType type : BoundType.values()) {
    assertNull(sortedMultiset.headMultiset(e0(), type).lastEntry());
    assertNull(sortedMultiset.tailMultiset(e0(), type).firstEntry());
  }
}
 
Example 28
Project: r01fb   File: Range.java   View source code 5 votes vote down vote up
public Range(final com.google.common.collect.Range<T> range) {
	_range = range;
	_upperBound = range.hasUpperBound() ? range.upperEndpoint() : null;
	_lowerBound = range.hasLowerBound() ? range.lowerEndpoint() : null;
	
	_upperBoundType = range.hasUpperBound() ? range.upperBoundType() : BoundType.OPEN;
	_lowerBoundType = range.hasLowerBound() ? range.lowerBoundType() : BoundType.OPEN;
}
 
Example 29
Project: r01fb   File: Range.java   View source code 5 votes vote down vote up
public Range(final T lower,final BoundType lowerBoundType,
			 final T upper,final BoundType upperBoundType) {
	// store the lower and upper bounds
	_lowerBound = lower;
	_upperBound = upper;
	
	_lowerBoundType = lowerBoundType;
	_upperBoundType = upperBoundType;
	
	// Create the delegate
	if (_lowerBound != null && _upperBound != null) {
		if (lowerBoundType == BoundType.OPEN && upperBoundType == BoundType.OPEN) { 
			_range = com.google.common.collect.Range.open(_lowerBound,_upperBound);
		} else if (lowerBoundType == BoundType.OPEN && upperBoundType == BoundType.CLOSED) {
			_range = com.google.common.collect.Range.openClosed(_lowerBound,_upperBound);
		} else if (lowerBoundType == BoundType.CLOSED && upperBoundType == BoundType.CLOSED) {
			_range = com.google.common.collect.Range.closed(_lowerBound,_upperBound);
		} else if (lowerBoundType == BoundType.CLOSED && upperBoundType == BoundType.OPEN) {
			_range = com.google.common.collect.Range.closedOpen(_lowerBound,_upperBound);
		} else {
			throw new IllegalArgumentException("Both lower and upper bound types MUST be provided!");
		}
	} else if (_lowerBound != null) {
		if (lowerBoundType == BoundType.OPEN) {
			_range = com.google.common.collect.Range.greaterThan(_lowerBound);
		} else {
			_range = com.google.common.collect.Range.atLeast(_lowerBound);
		}
	} else if (_upperBound != null) {
		if (upperBoundType == BoundType.OPEN) {
			_range = com.google.common.collect.Range.lessThan(_upperBound);
		} else {
			_range = com.google.common.collect.Range.atMost(_upperBound);
		}
	} else {
		throw new IllegalArgumentException("Cannot create range, at least lower or upper bound SHOULD be not null");
	}
}
 
Example 30
Project: r01fb   File: Range.java   View source code 5 votes vote down vote up
private static Range<Date> _parseDateRange(final String lowerBound,final BoundType lowerBoundType,
										   final String upperBound,final BoundType upperBoundType) {
	Date lowerBoundDate = lowerBound != null ? Dates.fromMillis(Long.parseLong(lowerBound)) : null;
	Date upperBoundDate = upperBound != null ? Dates.fromMillis(Long.parseLong(upperBound)) : null;
	return new Range<Date>(lowerBoundDate,lowerBoundType,
						   upperBoundDate,upperBoundType);
}
 
Example 31
Project: r01fb   File: Range.java   View source code 5 votes vote down vote up
private static Range<Byte>  _parseByteRange(final String lowerBound,final BoundType lowerBoundType,
										    final String upperBound,final BoundType upperBoundType) {
	Byte lowerBoundByte = lowerBound != null ? Byte.valueOf(lowerBound) : null;
	Byte upperBoundByte = upperBound != null ? Byte.valueOf(upperBound) : null;
	return new Range<Byte>(lowerBoundByte,lowerBoundType,
						   upperBoundByte,upperBoundType);
}
 
Example 32
Project: r01fb   File: Range.java   View source code 5 votes vote down vote up
private static Range<Integer>  _parseIntRange(final String lowerBound,final BoundType lowerBoundType,
										   	  final String upperBound,final BoundType upperBoundType) {
	Integer lowerBoundInt = lowerBound != null ? Integer.valueOf(lowerBound) : null;
	Integer upperBoundInt = upperBound != null ? Integer.valueOf(upperBound) : null;
	return new Range<Integer>(lowerBoundInt,lowerBoundType,
						      upperBoundInt,upperBoundType);
}
 
Example 33
Project: r01fb   File: Range.java   View source code 5 votes vote down vote up
private static Range<Short>  _parseShortRange(final String lowerBound,final BoundType lowerBoundType,
										   	  final String upperBound,final BoundType upperBoundType) {
	Short lowerBoundShort = lowerBound != null ? Short.valueOf(lowerBound) : null;
	Short upperBoundShort = upperBound != null ? Short.valueOf(upperBound) : null;
	return new Range<Short>(lowerBoundShort,lowerBoundType,
						    upperBoundShort,upperBoundType);
}
 
Example 34
Project: r01fb   File: Range.java   View source code 5 votes vote down vote up
private static Range<Long>  _parseLongRange(final String lowerBound,final BoundType lowerBoundType,
										    final String upperBound,final BoundType upperBoundType) {
	Long lowerBoundLong = lowerBound != null ? Long.valueOf(lowerBound) : null;
	Long upperBoundLong = upperBound != null ? Long.valueOf(upperBound) : null;
	return new Range<Long>(lowerBoundLong,lowerBoundType,
						   upperBoundLong,upperBoundType);
}
 
Example 35
Project: r01fb   File: Range.java   View source code 5 votes vote down vote up
private static Range<Double>  _parseDoubleRange(final String lowerBound,final BoundType lowerBoundType,
										   		final String upperBound,final BoundType upperBoundType) {
	Double lowerBoundDouble = lowerBound != null ? Double.valueOf(lowerBound) : null;
	Double upperBoundDouble = upperBound != null ? Double.valueOf(upperBound) : null;
	return new Range<Double>(lowerBoundDouble,lowerBoundType,
						     upperBoundDouble,upperBoundType);
}
 
Example 36
Project: r01fb   File: Range.java   View source code 5 votes vote down vote up
private static Range<Float>  _parseFloatRange(final String lowerBound,final BoundType lowerBoundType,
										   	  final String upperBound,final BoundType upperBoundType) {
	Float lowerBoundFloat = lowerBound != null ? Float.valueOf(lowerBound) : null;
	Float upperBoundFloat = upperBound != null ? Float.valueOf(upperBound) : null;
	return new Range<Float>(lowerBoundFloat,lowerBoundType,
						    upperBoundFloat,upperBoundType);
}
 
Example 37
Project: r01fb   File: Range.java   View source code 5 votes vote down vote up
public String asString() {
	RangeDef rangeDef = null;
	Class<T> dataType = Range.guessDataType(this);
	/// Compilation errors:  Incomparable Types
	//[javac] /softbase_ejie/aplic/r01fb/tmp/compileLib/r01fbClasses/src/r01f/types/Range.java:407: 
	//incomparable types: java.lang.Class<T> and java.lang.Class<java.util.Date>
    // [javac] 		if (dataType == java.util.Date.class || dataType == java.sql.Date.class) {
	
	Class<?> java_util_Date_class = java.util.Date.class;
	Class<?> java_sql_Date_class = java.sql.Date.class;
	Class<?> java_lang_Byte_class = Byte.class;
	Class<?> java_lang_Integer_class = Integer.class;
	Class<?> java_lang_Short_class = Short.class;
	Class<?> java_lang_Long_class = Long.class;
	Class<?> java_lang_Double_class = Double.class;
	Class<?> java_lang_Float_class = Float.class;
	
	if (dataType == java_util_Date_class || dataType == java_sql_Date_class) {
		rangeDef = _toDateBoundStrings(this);
	} else if (dataType == java_lang_Byte_class) {
		rangeDef = _toByteBoundStrings(this);
	} else if (dataType == java_lang_Integer_class) {
		rangeDef = _toIntegerBoundStrings(this);
	} else if (dataType == java_lang_Short_class) {
		rangeDef = _toShortBoundStrings(this);
	} else if (dataType == java_lang_Long_class ) {
		rangeDef = _toLongBoundStrings(this);
	} else if (dataType == java_lang_Double_class ) {
		rangeDef = _toDoubleBoundStrings(this);
	} else if (dataType == java_lang_Float_class) {
		rangeDef = _toFloatBoundStrings(this);
	} else {
		throw new IllegalArgumentException("Type " + dataType + " is NOT supported in Range");
	}
	String outStr = Strings.of("{}{}..{}{}")
						   .customizeWith((rangeDef.getLowerBoundType() == BoundType.CLOSED ? "[" : "("),(rangeDef.getLowerBound() != null ? rangeDef.getLowerBound() : ""),
								          (rangeDef.getUpperBound() != null ? rangeDef.getUpperBound() : ""),(rangeDef.getUpperBoundType() == BoundType.CLOSED ? "]" : ")"))
						   .asString();
	return outStr;
}
 
Example 38
Project: r01fb   File: LuceneSearchQuery.java   View source code 5 votes vote down vote up
private static Query _queryClauseFrom(final EqualsQueryClause<?> eqQry) {
	if (eqQry == null || eqQry.getValue() == null) return null;
	
	IndexDocumentFieldID luceneFieldId = IndexDocumentFieldID.forId(eqQry.getFieldId().asString());
	
	Query outQry = null;
	if (eqQry.isTextEquals()) {
		outQry = _matchTermQuery(luceneFieldId,
								 eqQry.getValue().toString());
		
	} else if (eqQry.isNumberEquals()) {
		outQry = _numberEqualsQuery(luceneFieldId,
									eqQry.getValueAsNumber(),
									eqQry.getNumberType());
	} else if (eqQry.isDateEquals()) {
		outQry = _numberInRangeQuery(luceneFieldId,
									 _createRange(eqQry.getDateMilis(),BoundType.CLOSED,eqQry.getDateMilis(),BoundType.CLOSED),
									 Long.class);
	} else if (eqQry.isEnumWithCodeEquals()) {
		EnumWithCode<?,?> enumWithCode = (EnumWithCode<?,?>)eqQry.getValue();
		String codeAsString = enumWithCode.getCode().toString();
		outQry = _matchKeywordQuery(luceneFieldId,
						   			codeAsString);
	} else if (eqQry.isEnumEquals()) {
		Enum<?> enumSimple = (Enum<?>)eqQry.getValue();
		String enumAsString = enumSimple.name();
		outQry = _matchKeywordQuery(luceneFieldId,
						   			enumAsString);
	} else if (eqQry.isOIDEquals()) {
		OID oid = (OID)eqQry.getValue();
		String oidAsString = oid.asString();
		outQry = _matchKeywordQuery(luceneFieldId,
									oidAsString);
	} else {
		throw new IllegalArgumentException();
	}
	return outQry;
}
 
Example 39
Project: r01fb   File: LuceneSearchQuery.java   View source code 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private static <N extends Number & Comparable> Query _numberInRangeQuery(final IndexDocumentFieldID fieldId,
																		 final Range<N> range,
																		 final Class<N> numberType) {
	boolean lowerIncluded = range.hasLowerBound() && range.lowerBoundType() == BoundType.CLOSED;
	boolean upperIncluded = range.hasUpperBound() && range.upperBoundType() == BoundType.CLOSED;
	
	N lowerBound = range.hasLowerBound() ? range.lowerEndpoint() : null;
	N upperBound = range.hasUpperBound() ? range.upperEndpoint() : null;
	
	Query outNumberEqQry = null;
	 if (numberType.equals(Integer.class)) {
		outNumberEqQry = NumericRangeQuery.newIntRange(fieldId.asString(),
													   (Integer)lowerBound,(Integer)upperBound, 
													   lowerIncluded,upperIncluded);
	 } else if (numberType.equals(Long.class)) {
		outNumberEqQry = NumericRangeQuery.newLongRange(fieldId.asString(),
														(Long)lowerBound,(Long)upperBound, 
														lowerIncluded,upperIncluded);
	} else if (numberType.equals(Double.class)) {
		outNumberEqQry = NumericRangeQuery.newDoubleRange(fieldId.asString(),
													      (Double)lowerBound,(Double)upperBound, 
													      lowerIncluded,upperIncluded);			
	} else if (numberType.equals(Float.class)) {
		outNumberEqQry = NumericRangeQuery.newFloatRange(fieldId.asString(),
													      (Float)lowerBound,(Float)upperBound, 
													      lowerIncluded,upperIncluded);
	}
	return outNumberEqQry;
}
 
Example 40
Project: gondola   File: BucketManager.java   View source code 5 votes vote down vote up
public ShardState lookupBucketTable(Range<Integer> range) {
    Map<Range<Integer>, ShardState> rangeMaps = bucketMap.subRangeMap(range).asMapOfRanges();
    if (rangeMaps.size() > 1) {
        boolean same = true;
        ShardState prev = null;
        for (Map.Entry<Range<Integer>, ShardState> e : rangeMaps.entrySet()) {
            Range<Integer> r = e.getKey();
            if (r.upperEndpoint() - r.lowerEndpoint() <= 1 && r.lowerBoundType() == BoundType.OPEN
                && r.upperBoundType() == BoundType.OPEN) {
                continue;
            }
            if (prev != null && !prev.equals(e.getValue())) {
                same = false;
                break;

            }
            prev = e.getValue();
        }
        if (!same) {
            throw new IllegalStateException(
                "Overlapped range found - inputRange=" + range + " ranges=" + rangeMaps.toString());
        }
        return prev;
    } else if (rangeMaps.size() == 0) {
        return null;
    }
    return rangeMaps.values().stream().findFirst().get();
}