Example usage for com.google.common.collect Range upperEndpoint

List of usage examples for com.google.common.collect Range upperEndpoint

Introduction

In this page you can find the example usage for com.google.common.collect Range upperEndpoint.

Prototype

public C upperEndpoint() 

Source Link

Document

Returns the upper endpoint of this range.

Usage

From source file:com.wealdtech.utils.RangeFormatter.java

/**
 * Format the dates of a date/time range.
 *
 * @param range the range to format/*  w  ww .  j  a v a2  s. co  m*/
 * @return the formatted range, or {@code null} if the input is {@code null}
 */
@Nullable
public String formatDate(@Nullable final Range<DateTime> range) {
    if (range == null || style == Style.TIME_ONLY) {
        return null;
    }

    final DateTime curDateTime = DateTime.now();
    final StringBuilder sb = new StringBuilder(64);

    // Dates.  Note that because we are working with dates and dates are closed/open we need to take a day away from the upper
    // date to make the format look right
    final DateTime lower = range.lowerEndpoint();
    final DateTime upper = range.upperEndpoint().minusDays(1);
    if (upper.isBefore(lower)) {
        throw new DataError.Bad("Upper part of range must be after lower part of range");
    }

    final boolean singleDay = isSameDay(lower, upper);

    // Lower date
    final Details lowerDetails = new Details();
    lowerDetails.showTime = false;
    lowerDetails.showDayOfWeek = true;
    lowerDetails.showDayOfMonth = true;

    if (!isSameMonth(lower, upper) || singleDay) {
        lowerDetails.showMonthOfYear = true;
    }
    if ((!isSameYear(lower, curDateTime)) && (singleDay || !isSameYear(lower, upper))) {
        lowerDetails.showYear = true;
    }
    sb.append(doFormat(lower, lowerDetails));

    if (!isSameDay(lower, upper)) {
        sb.append(" - ");

        final Details upperDetails = new Details();
        upperDetails.showTime = false;
        upperDetails.showDayOfWeek = true;
        upperDetails.showDayOfMonth = true;
        upperDetails.showMonthOfYear = true;
        if ((!isSameYear(lower, upper)) || (!isSameYear(upper, curDateTime))) {
            upperDetails.showYear = true;
        }

        sb.append(doFormat(upper, upperDetails));
    } else {
        // Need to append month and year if applicable
        if (!isSameMonth(lower, curDateTime)) {
            lowerDetails.showMonthOfYear = true;
        }
        if (!isSameYear(lower, curDateTime)) {
            lowerDetails.showYear = true;
        }
    }

    return sb.toString();
}

From source file:coolmap.application.widget.impl.WidgetUserGroup.java

private void init() {

    table.getTableHeader().setReorderingAllowed(false);
    table.setAutoCreateRowSorter(true);/*from  ww  w.jav a2 s.  co  m*/
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                    column);
            if (isSelected) {
                return label;
            }

            if (column == 1) {
                try {
                    label.setBackground(
                            nodeColor.get(table.getModel().getValueAt(table.convertRowIndexToModel(row), 0)));
                } catch (Exception e) {

                }
            } else {
                label.setBackground(UI.colorWhite);
            }

            return label;
        }

    });
    //Need a search box as well.

    //
    getContentPane().setLayout(new BorderLayout());

    //
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    JToolBar t = new JToolBar();
    getContentPane().add(t, BorderLayout.NORTH);
    t.setFloatable(false);

    try {
        //also add an action to add group nodes
        JMenuItem item = new JMenuItem("selected row nodes");
        item.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                CoolMapObject o = CoolMapMaster.getActiveCoolMapObject();
                if (o == null) {
                    return;
                }

                ArrayList<Range<Integer>> selected = o.getCoolMapView().getSelectedRows();
                ArrayList<VNode> selectedNodes = new ArrayList<>();

                for (Range<Integer> r : selected) {
                    for (int i = r.lowerEndpoint(); i < r.upperEndpoint(); i++) {
                        selectedNodes.add(o.getViewNodeRow(i));
                    }
                }

                createNewGroup(selectedNodes);

                //create a group
            }
        });
        WidgetMaster.getViewport().addPopupMenuItem("Create group", item, false);

        item = new JMenuItem("selected column nodes");
        item.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                CoolMapObject o = CoolMapMaster.getActiveCoolMapObject();
                if (o == null) {
                    return;
                }

                ArrayList<Range<Integer>> selected = o.getCoolMapView().getSelectedColumns();
                ArrayList<VNode> selectedNodes = new ArrayList<>();

                for (Range<Integer> r : selected) {
                    for (int i = r.lowerEndpoint(); i < r.upperEndpoint(); i++) {
                        selectedNodes.add(o.getViewNodeColumn(i));
                    }
                }

                createNewGroup(selectedNodes);

            }
        });
        WidgetMaster.getViewport().addPopupMenuItem("Create group", item, false);
    } catch (Exception e) {
        //
        //Error handling.
    }

}

From source file:org.openmhealth.dsu.repository.MongoDataPointRepositoryImpl.java

void addCreationTimestampCriteria(Query query, Range<OffsetDateTime> timestampRange) {

    if (timestampRange.hasLowerBound() || timestampRange.hasUpperBound()) {

        Criteria timestampCriteria = where("header.creation_date_time");

        if (timestampRange.hasLowerBound()) {
            if (timestampRange.lowerBoundType() == CLOSED) {
                timestampCriteria = timestampCriteria.gte(timestampRange.lowerEndpoint());
            } else {
                timestampCriteria = timestampCriteria.gt(timestampRange.lowerEndpoint());
            }/*w ww.jav a  2  s  . c  om*/
        }

        if (timestampRange.hasUpperBound()) {
            if (timestampRange.upperBoundType() == CLOSED) {
                timestampCriteria = timestampCriteria.lte(timestampRange.upperEndpoint());
            } else {
                timestampCriteria = timestampCriteria.lt(timestampRange.upperEndpoint());
            }
        }

        query.addCriteria(timestampCriteria);
    }
}

From source file:com.google.android.apps.forscience.whistlepunk.sensordb.SensorDatabaseImpl.java

/**
 * Gets the selection string and selectionArgs based on the tag, range and resolution tier.
 *
 * @return a pair where the first element is the selection string and the second element is the
 * array of selectionArgs./* www.  j  a  va 2s . c o m*/
 */
private Pair<String, String[]> getSelectionAndArgs(String sensorTag, TimeRange range, int resolutionTier) {
    List<String> clauses = new ArrayList<>();
    List<String> values = new ArrayList<>();

    clauses.add(ScalarSensorsTable.Column.TAG + " = ?");
    values.add(sensorTag);

    if (resolutionTier >= 0) {
        clauses.add(ScalarSensorsTable.Column.RESOLUTION_TIER + " = ?");
        values.add(String.valueOf(resolutionTier));
    }

    Range<Long> times = range.getTimes();
    Range<Long> canonicalTimes = times.canonical(DiscreteDomain.longs());
    if (canonicalTimes.hasLowerBound()) {
        String comparator = (canonicalTimes.lowerBoundType() == BoundType.CLOSED) ? " >= ?" : " > ?";
        clauses.add(ScalarSensorsTable.Column.TIMESTAMP_MILLIS + comparator);
        values.add(String.valueOf(canonicalTimes.lowerEndpoint()));
    }
    if (canonicalTimes.hasUpperBound()) {
        String comparator = (canonicalTimes.upperBoundType() == BoundType.CLOSED) ? " =< ?" : " < ?";
        clauses.add(ScalarSensorsTable.Column.TIMESTAMP_MILLIS + comparator);
        values.add(String.valueOf(canonicalTimes.upperEndpoint()));
    }

    return new Pair<>(Joiner.on(" AND ").join(clauses), values.toArray(new String[values.size()]));
}

From source file:net.sf.mzmine.project.impl.StorableScan.java

/**
 * @return Returns scan datapoints within a given range
 *///from  ww  w . j av a 2s.c o m
public @Nonnull DataPoint[] getDataPointsByMass(@Nonnull Range<Double> mzRange) {

    DataPoint dataPoints[] = getDataPoints();

    int startIndex, endIndex;
    for (startIndex = 0; startIndex < dataPoints.length; startIndex++) {
        if (dataPoints[startIndex].getMZ() >= mzRange.lowerEndpoint()) {
            break;
        }
    }

    for (endIndex = startIndex; endIndex < dataPoints.length; endIndex++) {
        if (dataPoints[endIndex].getMZ() > mzRange.upperEndpoint()) {
            break;
        }
    }

    DataPoint pointsWithinRange[] = new DataPoint[endIndex - startIndex];

    // Copy the relevant points
    System.arraycopy(dataPoints, startIndex, pointsWithinRange, 0, endIndex - startIndex);

    return pointsWithinRange;
}

From source file:com.google.eclipse.protobuf.validation.ProtobufJavaValidator.java

private void errorOnConflicts(Range<Long> range, Multimap<EObject, Range<Long>> rangeUsages,
        EObject errorSource, EStructuralFeature errorFeature) {
    for (Map.Entry<EObject, Range<Long>> rangeUsage : rangeUsages.entries()) {
        Range<Long> usedRange = rangeUsage.getValue();
        if (range.isConnected(usedRange)) {
            EObject rangeUser = rangeUsage.getKey();

            boolean rangeIsSingular = range.hasUpperBound() && range.upperEndpoint() == range.lowerEndpoint();
            String template = rangeIsSingular ? tagNumberConflict : tagNumberRangeConflict;

            String rangeUserString;
            String usedRangeString = rangeToString(usedRange);
            if (rangeUser instanceof MessageField) {
                rangeUserString = String.format(conflictingField, nameResolver.nameOf(rangeUser),
                        usedRangeString);
            } else if (rangeUser instanceof Group) {
                rangeUserString = String.format(conflictingGroup, nameResolver.nameOf(rangeUser),
                        usedRangeString);
            } else if (rangeUser instanceof Reserved) {
                rangeUserString = String.format(conflictingReservedNumber, usedRangeString);
            } else {
                rangeUserString = String.format(conflictingExtensions, usedRangeString);
            }/* ww w  . ja v  a 2 s . co m*/

            String message = String.format(template, rangeToString(range), rangeUserString);
            error(message, errorSource, errorFeature);

            // Don't report more than one error per element.
            return;
        }
    }
}

From source file:com.nimbits.client.io.http.NimbitsClientImpl.java

@Override
public List<Value> getSeries(final String entity, final Range<Date> range) {

    final Gson gson = GsonFactory.getInstance(true);

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(instanceUrl.getUrl())
            .setRequestInterceptor(requestInterceptor).setConverter(new GsonConverter(gson)).build();

    SeriesApi seriesApi = restAdapter.create(SeriesApi.class);

    List<Value> sample = seriesApi.getSeries(entity, range.lowerEndpoint().getTime(),
            range.upperEndpoint().getTime());

    List<Value> fixed = new ArrayList<Value>(sample.size());
    Set<Long> test = new HashSet<Long>(sample.size());
    for (Value value : sample) {
        if (!test.contains(value.getTimestamp().getTime())) {
            fixed.add(value);//from   ww  w  . ja v a  2  s .c o  m
            test.add(value.getTimestamp().getTime());
        }

    }
    return ImmutableList.copyOf(sample);

}

From source file:com.github.fge.grappa.matchers.join.JoinMatcherBuilder.java

/**
 * Generic method to build a {@link JoinMatcher}
 *
 * <p>You can use this method directly; note however that the range you will
 * pass as an argument will be {@link Range#intersection(Range) intersected}
 * with {@code Range.atLeast(0)}; if the result of the intersection is an
 * {@link Range#isEmpty() empty range}, this is an error condition.</p>
 *
 * <p>Ranges which are {@link BoundType#OPEN open} on any end will be turned
 * to closed range using {@link Range#canonical(DiscreteDomain)}.</p>
 *
 * @param range the range (must not be null)
 * @return a rule/*from  w  w w. ja  v a  2 s  .  c  o m*/
 * @throws IllegalArgumentException see description
 *
 * @see Range#canonical(DiscreteDomain)
 */
// TODO: check that it actually has an effect
@Cached
public Rule range(@Nonnull Range<Integer> range) {
    Objects.requireNonNull(range, "range must not be null");
    /*
     * We always intersect with that range...
     */
    Range<Integer> realRange = AT_LEAST_ZERO.intersection(range);

    /*
     * Empty ranges not allowed (what are we supposed to do with that
     * anyway?)
     */
    Preconditions.checkArgument(!realRange.isEmpty(),
            "illegal range " + range + ": should not be empty after intersection with " + AT_LEAST_ZERO);

    /*
     * Given that we intersect with AT_LEAST_ZERO, which has a lower bound,
     * the range will always have a lower bound. We want a closed range
     * internally, therefore change it if it is open.
     */
    Range<Integer> closedRange = toClosedRange(realRange);

    /*
     * We always have a lower bound
     */
    int lowerBound = closedRange.lowerEndpoint();

    /*
     * Handle the case where there is no upper bound
     */
    if (!closedRange.hasUpperBound())
        return new BoundedDownJoinMatcher(joined, joining, lowerBound);

    /*
     * There is an upper bound. Handle the case where it is 0 or 1. Since
     * the range is legal, we know that if it is 0, so is the lowerbound;
     * and if it is one, the lower bound is either 0 or 1.
     */
    int upperBound = closedRange.upperEndpoint();
    if (upperBound == 0)
        return new EmptyMatcher();
    if (upperBound == 1)
        return lowerBound == 0 ? new OptionalMatcher(joined) : joined;

    /*
     * So, upper bound is 2 or greater; return the appropriate matcher
     * according to what the lower bound is.
     *
     * Also, if the lower and upper bounds are equal, return a matcher doing
     * a fixed number of matches.
     */
    if (lowerBound == 0)
        return new BoundedUpJoinMatcher(joined, joining, upperBound);

    return lowerBound == upperBound ? new ExactMatchesJoinMatcher(joined, joining, lowerBound)
            : new BoundedBothJoinMatcher(joined, joining, lowerBound, upperBound);
}

From source file:jetbrains.jetpad.hybrid.BaseHybridSynchronizer.java

public void select(Range<Integer> sel) {
    mySelectionSupport.select(myTargetList.get(sel.lowerEndpoint()), myTargetList.get(sel.upperEndpoint() - 1));
}

From source file:org.sosy_lab.cpachecker.cpa.arg.ARGPathExport.java

private String tokensToText(Set<Integer> tokens) {
    StringBuilder result = new StringBuilder();
    RangeSet<Integer> tokenRanges = TreeRangeSet.create();
    for (Integer token : tokens) {
        tokenRanges.add(Range.closed(token, token));
    }/* ww w  .  j av  a2s. c  o m*/
    for (Range<Integer> range : tokenRanges.asRanges()) {
        if (result.length() > 0) {
            result.append(",");
        }
        Integer from = range.lowerEndpoint();
        Integer to = range.upperEndpoint();
        if (to - from == 0) {
            result.append(from);
        } else {
            result.append(from);
            result.append("-");
            result.append(to);
        }
    }

    return result.toString();
}