Java Code Examples for com.google.common.collect.Range#range()

The following examples show how to use com.google.common.collect.Range#range() . 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: PulsarWebResource.java    From pulsar with Apache License 2.0 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
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 3
Source File: Support.java    From immutables with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> Range<Comparable<Object>> writable(
    Encoder<T> encoder,
    Range<T> range) {
  if (range.hasLowerBound() && range.hasUpperBound()) {
    return Range.range(
        (Comparable<Object>) writable(encoder, range.lowerEndpoint()),
        range.lowerBoundType(),
        (Comparable<Object>) writable(encoder, range.upperEndpoint()),
        range.upperBoundType());
  } else if (range.hasLowerBound()) {
    return Range.downTo(
        (Comparable<Object>) writable(encoder, range.lowerEndpoint()),
        range.lowerBoundType());
  } else if (range.hasUpperBound()) {
    return Range.upTo(
        (Comparable<Object>) writable(encoder, range.upperEndpoint()),
        range.upperBoundType());
  }
  throw new AssertionError();
}
 
Example 4
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 5
Source File: Condition.java    From sharding-jdbc-1.5.1 with Apache License 2.0 5 votes vote down vote up
/**
 * 将条件对象转换为分片值.
 *
 * @param parameters 参数列表
 * @return 分片值
 */
public ShardingValue<?> getShardingValue(final List<Object> parameters) {
    List<Comparable<?>> conditionValues = getValues(parameters);
    switch (operator) {
        case EQUAL:
            return new ShardingValue<Comparable<?>>(column.getTableName(), column.getName(), conditionValues.get(0));
        case IN:
            return new ShardingValue<>(column.getTableName(), column.getName(), conditionValues);
        case BETWEEN:
            return new ShardingValue<>(column.getTableName(), column.getName(), Range.range(conditionValues.get(0), BoundType.CLOSED, conditionValues.get(1), BoundType.CLOSED));
        default:
            throw new UnsupportedOperationException(operator.getExpression());
    }
}
 
Example 6
Source File: ServiceUnitZkUtils.java    From pulsar with Apache License 2.0 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 7
Source File: NamespaceBundles.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public NamespaceBundles(NamespaceName nsname, long[] partitions, NamespaceBundleFactory factory, long version) {
    // check input arguments
    this.nsname = checkNotNull(nsname);
    this.factory = checkNotNull(factory);
    this.version = version;
    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 8
Source File: NamespaceBundleFactory.java    From pulsar with Apache License 2.0 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 9
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 10
Source File: TICVisualizerWindow.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
void updateTitle() {

    NumberFormat rtFormat = MZmineCore.getConfiguration().getRTFormat();
    NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
    NumberFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();

    StringBuffer mainTitle = new StringBuffer();
    StringBuffer subTitle = new StringBuffer();

    // If all data files have m/z range less than or equal to range of
    // the plot (mzMin, mzMax), then call this TIC, otherwise XIC
    Set<RawDataFile> fileSet = ticDataSets.keySet();
    String ticOrXIC = "TIC";

    // Enlarge range a bit to avoid rounding errors
    Range<Double> mzRange2 = Range.range(mzRange.lowerEndpoint() - 1, BoundType.CLOSED,
        mzRange.upperEndpoint() + 1, BoundType.CLOSED);
    for (RawDataFile df : fileSet) {
      if (!mzRange2.encloses(df.getDataMZRange())) {
        ticOrXIC = "XIC";
        break;
      }
    }

    if (plotType == TICPlotType.BASEPEAK) {
      if (ticOrXIC.equals("TIC")) {
        mainTitle.append("Base peak chromatogram");
      } else {
        mainTitle.append("XIC (base peak)");
      }
    } else {
      if (ticOrXIC.equals("TIC")) {
        mainTitle.append("TIC");
      } else {
        mainTitle.append("XIC");
      }
    }

    mainTitle.append(", m/z: " + mzFormat.format(mzRange.lowerEndpoint()) + " - "
        + mzFormat.format(mzRange.upperEndpoint()));

    CursorPosition pos = getCursorPosition();

    if (pos != null) {
      subTitle.append("Selected scan #");
      subTitle.append(pos.getScanNumber());
      if (ticDataSets.size() > 1) {
        subTitle.append(" (" + pos.getDataFile() + ")");
      }
      subTitle.append(", RT: " + rtFormat.format(pos.getRetentionTime()));
      if (plotType == TICPlotType.BASEPEAK) {
        subTitle.append(", base peak: " + mzFormat.format(pos.getMzValue()) + " m/z");
      }
      subTitle.append(", IC: " + intensityFormat.format(pos.getIntensityValue()));
    }

    // update window title
    RawDataFile files[] = ticDataSets.keySet().toArray(new RawDataFile[0]);
    Arrays.sort(files, new SimpleSorter());
    String dataFileNames = Joiner.on(",").join(files);
    setTitle("Chromatogram: [" + dataFileNames + "; " + mzFormat.format(mzRange.lowerEndpoint())
        + " - " + mzFormat.format(mzRange.upperEndpoint()) + " m/z" + "]");

    // update plot title
    ticPlot.setTitle(mainTitle.toString(), subTitle.toString());

  }
 
Example 11
Source File: XMLUtils.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Parse a range in the standard mathematical format e.g.
 *
 *     [0, 1) for a closed-open range from 0 to 1.
 *
 * Can also parse single numbers as a closed range e.g.
 *
 *     5 for a closed-closed range from 5 to 5.
 */
public static <T extends Number & Comparable<T>> Range<T> parseNumericRange(Node node, Class<T> type) throws InvalidXMLException {
    String value = node.getValue();

    Matcher matcher = RANGE_RE.matcher(value);
    if(!matcher.matches()) {
        T number = parseNumber(node, value, type, (T) null);
        if(number != null) {
            return Range.singleton(number);
        }
        throw new InvalidXMLException("Invalid " + type.getSimpleName().toLowerCase() + " range '" + value + "'", node);
    }

    T lower = parseNumber(node, matcher.group(2), type, true);
    T upper = parseNumber(node, matcher.group(3), type, true);

    BoundType lowerType = null, upperType = null;
    if(!Double.isInfinite(lower.doubleValue())) {
        lowerType = "(".equals(matcher.group(1)) ? BoundType.OPEN : BoundType.CLOSED;
    }
    if(!Double.isInfinite(upper.doubleValue())) {
        upperType = ")".equals(matcher.group(4)) ? BoundType.OPEN : BoundType.CLOSED;
    }

    if(lower.compareTo(upper) == 1) {
        throw new InvalidXMLException("range lower bound (" + lower + ") cannot be greater than upper bound (" + upper + ")", node);
    }

    if(lowerType == null) {
        if(upperType == null) {
            return Range.all();
        } else {
            return Range.upTo(upper, upperType);
        }
    } else {
        if(upperType == null) {
            return Range.downTo(lower, lowerType);
        } else {
            return Range.range(lower, lowerType, upper, upperType);
        }
    }
}
 
Example 12
Source File: XMLUtils.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static <T extends Number & Comparable<T>> Range<T> parseNumericRange(Element el, Class<T> type, Range<T> def) throws InvalidXMLException {
    Attribute lt = el.getAttribute("lt");
    Attribute lte = getAttribute(el, "lte", "max");
    Attribute gt = el.getAttribute("gt");
    Attribute gte = getAttribute(el, "gte", "min");

    if(lt != null && lte != null) throw new InvalidXMLException("Conflicting upper bound for numeric range", el);
    if(gt != null && gte != null) throw new InvalidXMLException("Conflicting lower bound for numeric range", el);

    BoundType lowerBoundType, upperBoundType;
    T lowerBound, upperBound;

    if(gt != null) {
        lowerBound = parseNumber(gt, type, (T) null);
        lowerBoundType = BoundType.OPEN;
    } else {
        lowerBound = parseNumber(gte, type, (T) null);
        lowerBoundType = BoundType.CLOSED;
    }

    if(lt != null) {
        upperBound = parseNumber(lt, type, (T) null);
        upperBoundType = BoundType.OPEN;
    } else {
        upperBound = parseNumber(lte, type, (T) null);
        upperBoundType = BoundType.CLOSED;
    }

    if(lowerBound == null) {
        if(upperBound == null) {
            return def;
        } else {
            return Range.upTo(upperBound, upperBoundType);
        }
    } else {
        if(upperBound == null) {
            return Range.downTo(lowerBound, lowerBoundType);
        } else {
            return Range.range(lowerBound, lowerBoundType, upperBound, upperBoundType);
        }
    }
}
 
Example 13
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends Comparable> Range<T> ofString(String str, Function<String, T> converter, Class<T> cls) {
    BoundType lowerBound = str.charAt(0) == '[' ? BoundType.CLOSED : BoundType.OPEN;
    BoundType upperBound = str.charAt(str.length() - 1) == ']' ? BoundType.CLOSED : BoundType.OPEN;

    int delim = str.indexOf(',');

    if (delim == -1) {
        throw new IllegalArgumentException("Cannot find comma character");
    }

    String lowerStr = str.substring(1, delim);
    String upperStr = str.substring(delim + 1, str.length() - 1);

    T lower = null;
    T upper = null;

    if (lowerStr.length() > 0) {
        lower = converter.apply(lowerStr);
    }

    if (upperStr.length() > 0) {
        upper = converter.apply(upperStr);
    }

    if (lower == null && upper == null) {
        throw new IllegalArgumentException("Cannot find bound type");
    }

    if (lowerStr.length() == 0) {
        return upperBound == BoundType.CLOSED ?
                Range.atMost(upper) :
                Range.lessThan(upper);
    } else if (upperStr.length() == 0) {
        return lowerBound == BoundType.CLOSED ?
                Range.atLeast(lower) :
                Range.greaterThan(lower);
    } else {
        return Range.range(lower, lowerBound, upper, upperBound);
    }
}
 
Example 14
Source File: RangeFactory.java    From jackson-datatypes-collections with Apache License 2.0 4 votes vote down vote up
public static <C extends Comparable<?>> Range<C> range(final C lowerEndpoint, final BoundType lowerBoundType,
                       final C upperEndpoint, final BoundType upperBoundType)
{
    return Range.range(lowerEndpoint, lowerBoundType, upperEndpoint, upperBoundType);
}
 
Example 15
Source File: TICVisualizerWindow.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
void updateTitle() {

    NumberFormat rtFormat = MZmineCore.getConfiguration().getRTFormat();
    NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
    NumberFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();

    StringBuffer mainTitle = new StringBuffer();
    StringBuffer subTitle = new StringBuffer();

    // If all data files have m/z range less than or equal to range of
    // the plot (mzMin, mzMax), then call this TIC, otherwise XIC
    Set<RawDataFile> fileSet = ticDataSets.keySet();
    String ticOrXIC = "TIC";

    // Enlarge range a bit to avoid rounding errors
    Range<Double> mzRange2 = Range.range(mzRange.lowerEndpoint() - 1, BoundType.CLOSED,
        mzRange.upperEndpoint() + 1, BoundType.CLOSED);
    for (RawDataFile df : fileSet) {
      if (!mzRange2.encloses(df.getDataMZRange())) {
        ticOrXIC = "XIC";
        break;
      }
    }

    if (plotType == TICPlotType.BASEPEAK) {
      if (ticOrXIC.equals("TIC")) {
        mainTitle.append("Base peak chromatogram");
      } else {
        mainTitle.append("XIC (base peak)");
      }
    } else {
      if (ticOrXIC.equals("TIC")) {
        mainTitle.append("TIC");
      } else {
        mainTitle.append("XIC");
      }
    }

    mainTitle.append(", m/z: " + mzFormat.format(mzRange.lowerEndpoint()) + " - "
        + mzFormat.format(mzRange.upperEndpoint()));

    CursorPosition pos = getCursorPosition();

    if (pos != null) {
      subTitle.append("Selected scan #");
      subTitle.append(pos.getScanNumber());
      if (ticDataSets.size() > 1) {
        subTitle.append(" (" + pos.getDataFile() + ")");
      }
      subTitle.append(", RT: " + rtFormat.format(pos.getRetentionTime()));
      if (plotType == TICPlotType.BASEPEAK) {
        subTitle.append(", base peak: " + mzFormat.format(pos.getMzValue()) + " m/z");
      }
      subTitle.append(", IC: " + intensityFormat.format(pos.getIntensityValue()));
    }

    // update window title
    RawDataFile files[] = ticDataSets.keySet().toArray(new RawDataFile[0]);
    Arrays.sort(files, new SimpleSorter());
    String dataFileNames = Joiner.on(",").join(files);
    setTitle("Chromatogram: [" + dataFileNames + "; " + mzFormat.format(mzRange.lowerEndpoint())
        + " - " + mzFormat.format(mzRange.upperEndpoint()) + " m/z" + "]");

    // update plot title
    ticPlot.setTitle(mainTitle.toString(), subTitle.toString());

  }