List of usage examples for com.google.common.collect Range lessThan
public static <C extends Comparable<?>> Range<C> lessThan(C endpoint)
From source file:org.apache.hadoop.hive.ql.optimizer.calcite.druid.DruidIntervalUtils.java
protected static List<Range> leafToRanges(RelDataType type, RexCall call, boolean withNot) { switch (call.getKind()) { case EQUALS:/* ww w. j ava 2 s . c o m*/ case LESS_THAN: case LESS_THAN_OR_EQUAL: case GREATER_THAN: case GREATER_THAN_OR_EQUAL: { RexLiteral literal = null; if (call.getOperands().get(0) instanceof RexInputRef && call.getOperands().get(1) instanceof RexLiteral) { literal = extractLiteral(call.getOperands().get(1)); } else if (call.getOperands().get(0) instanceof RexInputRef && call.getOperands().get(1).getKind() == SqlKind.CAST) { literal = extractLiteral(call.getOperands().get(1)); } else if (call.getOperands().get(1) instanceof RexInputRef && call.getOperands().get(0) instanceof RexLiteral) { literal = extractLiteral(call.getOperands().get(0)); } else if (call.getOperands().get(1) instanceof RexInputRef && call.getOperands().get(0).getKind() == SqlKind.CAST) { literal = extractLiteral(call.getOperands().get(0)); } if (literal == null) { return null; } Comparable value = literalToType(literal, type); if (value == null) { return null; } if (call.getKind() == SqlKind.LESS_THAN) { return Arrays.<Range>asList(withNot ? Range.atLeast(value) : Range.lessThan(value)); } else if (call.getKind() == SqlKind.LESS_THAN_OR_EQUAL) { return Arrays.<Range>asList(withNot ? Range.greaterThan(value) : Range.atMost(value)); } else if (call.getKind() == SqlKind.GREATER_THAN) { return Arrays.<Range>asList(withNot ? Range.atMost(value) : Range.greaterThan(value)); } else if (call.getKind() == SqlKind.GREATER_THAN_OR_EQUAL) { return Arrays.<Range>asList(withNot ? Range.lessThan(value) : Range.atLeast(value)); } else { //EQUALS if (!withNot) { return Arrays.<Range>asList(Range.closed(value, value)); } return Arrays.<Range>asList(Range.lessThan(value), Range.greaterThan(value)); } } case BETWEEN: { RexLiteral literal1 = extractLiteral(call.getOperands().get(2)); if (literal1 == null) { return null; } RexLiteral literal2 = extractLiteral(call.getOperands().get(3)); if (literal2 == null) { return null; } Comparable value1 = literalToType(literal1, type); Comparable value2 = literalToType(literal2, type); if (value1 == null || value2 == null) { return null; } boolean inverted = value1.compareTo(value2) > 0; if (!withNot) { return Arrays.<Range>asList(inverted ? Range.closed(value2, value1) : Range.closed(value1, value2)); } return Arrays.<Range>asList(Range.lessThan(inverted ? value2 : value1), Range.greaterThan(inverted ? value1 : value2)); } case IN: { List<Range> ranges = Lists.newArrayList(); for (int i = 1; i < call.getOperands().size(); i++) { RexLiteral literal = extractLiteral(call.getOperands().get(i)); if (literal == null) { return null; } Comparable element = literalToType(literal, type); if (element == null) { return null; } if (withNot) { ranges.addAll(Arrays.<Range>asList(Range.lessThan(element), Range.greaterThan(element))); } else { ranges.add(Range.closed(element, element)); } } return ranges; } default: return null; } }
From source file:org.openmhealth.shimmer.common.controller.DataPointSearchController.java
public Range<OffsetDateTime> asRange(OffsetDateTime onOrAfterDateTime, OffsetDateTime beforeDateTime) { if (onOrAfterDateTime != null && beforeDateTime != null) { return Range.closedOpen(onOrAfterDateTime, beforeDateTime); }/*from w w w.ja va 2 s . c o m*/ if (onOrAfterDateTime != null) { return Range.atLeast(onOrAfterDateTime); } else if (beforeDateTime != null) { return Range.lessThan(beforeDateTime); } return Range.all(); }
From source file:org.openmhealth.dsu.controller.DataPointController.java
/** * Reads data points./*from w w w. j a v a 2 s.c om*/ * * @param schemaNamespace the namespace of the schema the data points conform to * @param schemaName the name of the schema the data points conform to * @param schemaVersion the version of the schema the data points conform to * @param createdOnOrAfter the earliest creation timestamp of the data points to return, inclusive * @param createdBefore the latest creation timestamp of the data points to return, exclusive * @param offset the number of data points to skip * @param limit the number of data points to return * @return a list of matching data points */ // TODO confirm if HEAD handling needs anything additional // only allow clients with read scope to read data points @PreAuthorize("#oauth2.clientHasRole('" + CLIENT_ROLE + "') and #oauth2.hasScope('" + DATA_POINT_READ_SCOPE + "')") // TODO look into any meaningful @PostAuthorize filtering @RequestMapping(value = "/dataPoints", method = { HEAD, GET }, produces = APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<Iterable<DataPoint>> readDataPoints( @RequestParam(value = SCHEMA_NAMESPACE_PARAMETER) final String schemaNamespace, @RequestParam(value = SCHEMA_NAME_PARAMETER) final String schemaName, // TODO make this optional and update all associated code @RequestParam(value = SCHEMA_VERSION_PARAMETER) final String schemaVersion, // TODO replace with Optional<> in Spring MVC 4.1 @RequestParam(value = CREATED_ON_OR_AFTER_PARAMETER, required = false) final OffsetDateTime createdOnOrAfter, @RequestParam(value = CREATED_BEFORE_PARAMETER, required = false) final OffsetDateTime createdBefore, @RequestParam(value = RESULT_OFFSET_PARAMETER, defaultValue = "0") final Integer offset, @RequestParam(value = RESULT_LIMIT_PARAMETER, defaultValue = DEFAULT_RESULT_LIMIT) final Integer limit, Authentication authentication) { // TODO add validation or explicitly comment that this is handled using exception translators // determine the user associated with the access token to restrict the search accordingly String endUserId = getEndUserId(authentication); DataPointSearchCriteria searchCriteria = new DataPointSearchCriteria(endUserId, schemaNamespace, schemaName, schemaVersion); if (createdOnOrAfter != null && createdBefore != null) { searchCriteria.setCreationTimestampRange(Range.closedOpen(createdOnOrAfter, createdBefore)); } else if (createdOnOrAfter != null) { searchCriteria.setCreationTimestampRange(Range.atLeast(createdOnOrAfter)); } else if (createdBefore != null) { searchCriteria.setCreationTimestampRange(Range.lessThan(createdBefore)); } Iterable<DataPoint> dataPoints = dataPointService.findBySearchCriteria(searchCriteria, offset, limit); HttpHeaders headers = new HttpHeaders(); // FIXME add pagination headers // headers.set("Next"); // headers.set("Previous"); return new ResponseEntity<>(dataPoints, headers, OK); }
From source file:org.kiji.schema.impl.cassandra.CassandraKijiPartition.java
/** * Convert a set of (start-token, host) pairs into a set of (token-range, host) pairs. * * Package private for testing.//from w w w. jav a2 s. c o m * * @param startTokens The set of start tokens with hosts. * @return The token corresponding token ranges. */ static Map<Range<Long>, InetAddress> getTokenRanges(final SortedMap<Long, InetAddress> startTokens) { ImmutableMap.Builder<Range<Long>, InetAddress> tokenRangesBldr = ImmutableMap.builder(); final PeekingIterator<Entry<Long, InetAddress>> startTokensItr = Iterators .peekingIterator(startTokens.entrySet().iterator()); // Add a range for [-, firstStartToken) owned by the final key (the wrap-around range). // For more information on Casandra VNode token ranges: // http://www.datastax.com/dev/blog/virtual-nodes-in-cassandra-1-2 tokenRangesBldr.put(Range.lessThan(startTokens.firstKey()), startTokens.get(startTokens.lastKey())); while (startTokensItr.hasNext()) { Entry<Long, InetAddress> startToken = startTokensItr.next(); if (!startTokensItr.hasNext()) { // The final start token // Add a range for [lastStartToken, ) tokenRangesBldr.put(Range.atLeast(startToken.getKey()), startToken.getValue()); } else { // Add a range for [thisStartToken, nextStartToken) tokenRangesBldr.put(Range.closedOpen(startToken.getKey(), startTokensItr.peek().getKey()), startToken.getValue()); } } final Map<Range<Long>, InetAddress> tokenRanges = tokenRangesBldr.build(); // Check that the returned ranges are coherent; most importantly that all possible tokens fall // within the returned range set. if (startTokens.size() + 1 != tokenRanges.size()) { throw new InternalKijiError( String.format("Unexpected number of token ranges. start-tokens: %s, token-ranges: %s.", startTokens.size(), tokenRanges.size())); } final RangeSet<Long> ranges = TreeRangeSet.create(); for (Range<Long> tokenRange : tokenRanges.keySet()) { ranges.add(tokenRange); } if (!ranges.encloses(Range.closed(Long.MIN_VALUE, Long.MAX_VALUE))) { throw new InternalKijiError("Token range does not include all possible tokens."); } return tokenRanges; }
From source file:org.apache.druid.query.filter.InDimFilter.java
@Override public RangeSet<String> getDimensionRangeSet(String dimension) { if (!Objects.equals(getDimension(), dimension) || getExtractionFn() != null) { return null; }/*ww w . j av a 2s.c o m*/ RangeSet<String> retSet = TreeRangeSet.create(); for (String value : values) { String valueEquivalent = NullHandling.nullToEmptyIfNeeded(value); if (valueEquivalent == null) { // Case when SQL compatible null handling is enabled // Range.singleton(null) is invalid, so use the fact that // only null values are less than empty string. retSet.add(Range.lessThan("")); } else { retSet.add(Range.singleton(valueEquivalent)); } } return retSet; }
From source file:org.apache.druid.query.filter.BoundDimFilter.java
@Override public RangeSet<String> getDimensionRangeSet(String dimension) { if (!(Objects.equals(getDimension(), dimension) && getExtractionFn() == null && ordering.equals(StringComparators.LEXICOGRAPHIC))) { return null; }//from www. java 2s . c o m RangeSet<String> retSet = TreeRangeSet.create(); Range<String> range; if (getLower() == null) { range = isUpperStrict() ? Range.lessThan(getUpper()) : Range.atMost(getUpper()); } else if (getUpper() == null) { range = isLowerStrict() ? Range.greaterThan(getLower()) : Range.atLeast(getLower()); } else { range = Range.range(getLower(), isLowerStrict() ? BoundType.OPEN : BoundType.CLOSED, getUpper(), isUpperStrict() ? BoundType.OPEN : BoundType.CLOSED); } retSet.add(range); return retSet; }
From source file:org.openmhealth.dsu.controller.DataPointController.java
@PreAuthorize("#oauth2.clientHasRole('" + CLIENT_ROLE + "') and #oauth2.hasScope('" + DATA_POINT_READ_SCOPE + "')")//from w ww . j a v a 2s . c o m // TODO look into any meaningful @PostAuthorize filtering @RequestMapping(value = "/dataPoints/caregiver", method = { HEAD, GET }, produces = APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<Iterable<DataPoint>> readDataPointsCareGiver( @RequestParam(value = SCHEMA_NAMESPACE_PARAMETER) final String schemaNamespace, @RequestParam(value = SCHEMA_NAME_PARAMETER) final String schemaName, // TODO make this optional and update all associated code @RequestParam(value = SCHEMA_VERSION_PARAMETER) final String schemaVersion, @RequestParam(value = USER_ID) final String endUserId, @RequestParam(value = CAREGIVER_KEY) final String careGiverKey, // TODO replace with Optional<> in Spring MVC 4.1 @RequestParam(value = CREATED_ON_OR_AFTER_PARAMETER, required = false) final OffsetDateTime createdOnOrAfter, @RequestParam(value = CREATED_BEFORE_PARAMETER, required = false) final OffsetDateTime createdBefore, @RequestParam(value = RESULT_OFFSET_PARAMETER, defaultValue = "0") final Integer offset, @RequestParam(value = RESULT_LIMIT_PARAMETER, defaultValue = DEFAULT_RESULT_LIMIT) final Integer limit, Authentication authentication) { if (!careGiverKey.equals("someKey")) { return new ResponseEntity<>(NOT_ACCEPTABLE); } DataPointSearchCriteria searchCriteria = new DataPointSearchCriteria(endUserId, schemaNamespace, schemaName, schemaVersion); if (createdOnOrAfter != null && createdBefore != null) { searchCriteria.setCreationTimestampRange(Range.closedOpen(createdOnOrAfter, createdBefore)); } else if (createdOnOrAfter != null) { searchCriteria.setCreationTimestampRange(Range.atLeast(createdOnOrAfter)); } else if (createdBefore != null) { searchCriteria.setCreationTimestampRange(Range.lessThan(createdBefore)); } Iterable<DataPoint> dataPoints = dataPointService.findBySearchCriteria(searchCriteria, offset, limit); HttpHeaders headers = new HttpHeaders(); // FIXME add pagination headers // headers.set("Next"); // headers.set("Previous"); return new ResponseEntity<>(dataPoints, headers, OK); }
From source file:com.tinspx.util.io.callbacks.FileChannelCallback.java
/** * Normalizes lower bound to a closed bound type (if exists) and the * upper bound to an open bound type (if exists). Missing bounds remain * missing. Lower bound must be non-negative and upper bound must be * positive. The range cannot be empty./* w w w . j a va2s . co m*/ */ static Range<Long> checkAndNormalize(Range<Long> range) { checkArgument(!range.isEmpty(), "range %s is empty", range); boolean make = false; long lower = -1; long upper = -1; if (range.hasLowerBound()) { lower = range.lowerEndpoint(); if (range.lowerBoundType() == BoundType.OPEN) { make = true; lower++; } checkArgument(lower >= 0, "closed lower bound (%s) may not be negative", lower); } if (range.hasUpperBound()) { upper = range.upperEndpoint(); if (range.upperBoundType() == BoundType.CLOSED) { make = true; upper++; } checkArgument(upper > 0, "open upper bound (%s) must be positive", upper); } if (make) { if (lower >= 0) { if (upper > 0) { range = Range.closedOpen(lower, upper); } else { range = Range.atLeast(lower); } } else { assert upper > 0 : upper; range = Range.lessThan(upper); } checkArgument(!range.isEmpty(), "normalized range %s is empty", range); } return range; }
From source file:com.ibm.common.activitystreams.actions.Parameter.java
public <O extends Comparable<? super O>> Range<O> bounds() { O mini = minInclusive();//from w ww . jav a2 s .c om 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); } }
From source file:org.apache.calcite.rex.RexSimplify.java
private static RexNode processRange(RexBuilder rexBuilder, List<RexNode> terms, Map<String, Pair<Range, List<RexNode>>> rangeTerms, RexNode term, RexNode ref, RexLiteral constant, SqlKind comparison) {/*from w ww . j a va 2s . co m*/ final Comparable v0 = constant.getValue(); Pair<Range, List<RexNode>> p = rangeTerms.get(ref.toString()); if (p == null) { Range r; switch (comparison) { case EQUALS: r = Range.singleton(v0); break; case LESS_THAN: r = Range.lessThan(v0); break; case LESS_THAN_OR_EQUAL: r = Range.atMost(v0); break; case GREATER_THAN: r = Range.greaterThan(v0); break; case GREATER_THAN_OR_EQUAL: r = Range.atLeast(v0); break; default: throw new AssertionError(); } rangeTerms.put(ref.toString(), new Pair(r, ImmutableList.of(term))); } else { // Exists boolean removeUpperBound = false; boolean removeLowerBound = false; Range r = p.left; switch (comparison) { case EQUALS: if (!r.contains(v0)) { // Range is empty, not satisfiable return rexBuilder.makeLiteral(false); } rangeTerms.put(ref.toString(), new Pair(Range.singleton(v0), ImmutableList.of(term))); // remove terms.removeAll(p.right); break; case LESS_THAN: { int comparisonResult = 0; if (r.hasUpperBound()) { comparisonResult = v0.compareTo(r.upperEndpoint()); } if (comparisonResult <= 0) { // 1) No upper bound, or // 2) We need to open the upper bound, or // 3) New upper bound is lower than old upper bound if (r.hasLowerBound()) { if (v0.compareTo(r.lowerEndpoint()) < 0) { // Range is empty, not satisfiable return rexBuilder.makeLiteral(false); } // a <= x < b OR a < x < b r = Range.range(r.lowerEndpoint(), r.lowerBoundType(), v0, BoundType.OPEN); } else { // x < b r = Range.lessThan(v0); } if (r.isEmpty()) { // Range is empty, not satisfiable return rexBuilder.makeLiteral(false); } // remove prev upper bound removeUpperBound = true; } else { // Remove this term as it is contained in current upper bound terms.remove(term); } break; } case LESS_THAN_OR_EQUAL: { int comparisonResult = -1; if (r.hasUpperBound()) { comparisonResult = v0.compareTo(r.upperEndpoint()); } if (comparisonResult < 0) { // 1) No upper bound, or // 2) New upper bound is lower than old upper bound if (r.hasLowerBound()) { if (v0.compareTo(r.lowerEndpoint()) < 0) { // Range is empty, not satisfiable return rexBuilder.makeLiteral(false); } // a <= x <= b OR a < x <= b r = Range.range(r.lowerEndpoint(), r.lowerBoundType(), v0, BoundType.CLOSED); } else { // x <= b r = Range.atMost(v0); } if (r.isEmpty()) { // Range is empty, not satisfiable return rexBuilder.makeLiteral(false); } // remove prev upper bound removeUpperBound = true; } else { // Remove this term as it is contained in current upper bound terms.remove(term); } break; } case GREATER_THAN: { int comparisonResult = 0; if (r.hasLowerBound()) { comparisonResult = v0.compareTo(r.lowerEndpoint()); } if (comparisonResult >= 0) { // 1) No lower bound, or // 2) We need to open the lower bound, or // 3) New lower bound is greater than old lower bound if (r.hasUpperBound()) { if (v0.compareTo(r.upperEndpoint()) > 0) { // Range is empty, not satisfiable return rexBuilder.makeLiteral(false); } // a < x <= b OR a < x < b r = Range.range(v0, BoundType.OPEN, r.upperEndpoint(), r.upperBoundType()); } else { // x > a r = Range.greaterThan(v0); } if (r.isEmpty()) { // Range is empty, not satisfiable return rexBuilder.makeLiteral(false); } // remove prev lower bound removeLowerBound = true; } else { // Remove this term as it is contained in current lower bound terms.remove(term); } break; } case GREATER_THAN_OR_EQUAL: { int comparisonResult = 1; if (r.hasLowerBound()) { comparisonResult = v0.compareTo(r.lowerEndpoint()); } if (comparisonResult > 0) { // 1) No lower bound, or // 2) New lower bound is greater than old lower bound if (r.hasUpperBound()) { if (v0.compareTo(r.upperEndpoint()) > 0) { // Range is empty, not satisfiable return rexBuilder.makeLiteral(false); } // a <= x <= b OR a <= x < b r = Range.range(v0, BoundType.CLOSED, r.upperEndpoint(), r.upperBoundType()); } else { // x >= a r = Range.atLeast(v0); } if (r.isEmpty()) { // Range is empty, not satisfiable return rexBuilder.makeLiteral(false); } // remove prev lower bound removeLowerBound = true; } else { // Remove this term as it is contained in current lower bound terms.remove(term); } break; } default: throw new AssertionError(); } if (removeUpperBound) { ImmutableList.Builder<RexNode> newBounds = ImmutableList.builder(); for (RexNode e : p.right) { if (e.isA(SqlKind.LESS_THAN) || e.isA(SqlKind.LESS_THAN_OR_EQUAL)) { terms.remove(e); } else { newBounds.add(e); } } newBounds.add(term); rangeTerms.put(ref.toString(), new Pair(r, newBounds.build())); } else if (removeLowerBound) { ImmutableList.Builder<RexNode> newBounds = ImmutableList.builder(); for (RexNode e : p.right) { if (e.isA(SqlKind.GREATER_THAN) || e.isA(SqlKind.GREATER_THAN_OR_EQUAL)) { terms.remove(e); } else { newBounds.add(e); } } newBounds.add(term); rangeTerms.put(ref.toString(), new Pair(r, newBounds.build())); } } // Default return null; }