Java Code Examples for com.google.common.collect.Ordering#reverse()

The following examples show how to use com.google.common.collect.Ordering#reverse() . 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: OrderedResultIterator.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a comparator from the list of columns in ORDER BY clause.
 * @param orderByExpressions the columns in ORDER BY clause.
 * @return the comparator built from the list of columns in ORDER BY clause.
 */
// ImmutableBytesWritable.Comparator doesn't implement generics
@SuppressWarnings("unchecked")
private static Comparator<ResultEntry> buildComparator(List<OrderByExpression> orderByExpressions) {
    Ordering<ResultEntry> ordering = null;
    int pos = 0;
    for (OrderByExpression col : orderByExpressions) {
        Expression e = col.getExpression();
        Comparator<ImmutableBytesWritable> comparator = 
                e.getSortOrder() == SortOrder.DESC && !e.getDataType().isFixedWidth() 
                ? buildDescVarLengthComparator() 
                : new ImmutableBytesWritable.Comparator();
        Ordering<ImmutableBytesWritable> o = Ordering.from(comparator);
        if(!col.isAscending()) o = o.reverse();
        o = col.isNullsLast() ? o.nullsLast() : o.nullsFirst();
        Ordering<ResultEntry> entryOrdering = o.onResultOf(new NthKey(pos++));
        ordering = ordering == null ? entryOrdering : ordering.compound(entryOrdering);
    }
    return ordering;
}
 
Example 2
Source File: WorldSwitcherPanel.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
private int getCompareValue(WorldTableRow row1, WorldTableRow row2, Function<WorldTableRow, Comparable> compareByFn)
{
	Ordering<Comparable> ordering = Ordering.natural();
	if (!ascendingOrder)
	{
		ordering = ordering.reverse();
	}
	ordering = ordering.nullsLast();
	return ordering.compare(compareByFn.apply(row1), compareByFn.apply(row2));
}
 
Example 3
Source File: WorldSwitcherPanel.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int getCompareValue(WorldTableRow row1, WorldTableRow row2, Function<WorldTableRow, Comparable> compareByFn)
{
	Ordering<Comparable> ordering = Ordering.natural();
	if (!ascendingOrder)
	{
		ordering = ordering.reverse();
	}
	ordering = ordering.nullsLast();
	return ordering.compare(compareByFn.apply(row1), compareByFn.apply(row2));
}
 
Example 4
Source File: MergeIterator.java    From emodb with Apache License 2.0 5 votes vote down vote up
public static Iterator<Change> merge(Iterator<Change> iter1, Iterator<Change> iter2, boolean reversed) {
    if (!iter2.hasNext()) {
        return iter1;
    } else if (!iter1.hasNext()) {
        return iter2;
    }
    Ordering<UUID> ordering = TimeUUIDs.ordering();
    return new MergeIterator(iter1, iter2, reversed ? ordering.reverse() : ordering);
}
 
Example 5
Source File: OrderedResultIterator.java    From phoenix with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a comparator from the list of columns in ORDER BY clause.
 * @param orderByExpressions the columns in ORDER BY clause.
 * @return the comparator built from the list of columns in ORDER BY clause.
 */
// ImmutableBytesWritable.Comparator doesn't implement generics
@SuppressWarnings("unchecked")
private static Comparator<ResultEntry> buildComparator(List<OrderByExpression> orderByExpressions) {
    Ordering<ResultEntry> ordering = null;
    int pos = 0;
    for (OrderByExpression col : orderByExpressions) {
        Ordering<ImmutableBytesWritable> o = Ordering.from(new ImmutableBytesWritable.Comparator());
        if(!col.isAscending()) o = o.reverse();
        o = col.isNullsLast() ? o.nullsLast() : o.nullsFirst();
        Ordering<ResultEntry> entryOrdering = o.onResultOf(new NthKey(pos++));
        ordering = ordering == null ? entryOrdering : ordering.compound(entryOrdering);
    }
    return ordering;
}
 
Example 6
Source File: AbstractJavaSortableDataProvider.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<? extends T> iterator(long first, long count) {
	Collection<T> data =dataModel.getObject();
	if(data==null || data.size()==0) return Collections.emptyIterator();
	if(filterPredicate!=null) data = Collections2.filter(data, filterPredicate); 
	Iterator<T> it;
	final SortParam<S> sortParam = getSort();
	if(sortParam!=null && sortParam.getProperty()!=null)
	{
		Ordering<T> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<T, Comparable<?>>() {

			@Override
			public Comparable<?> apply(T input) {
				return comparableValue(input, sortParam.getProperty());
			}
		});
		if(!sortParam.isAscending()) ordering = ordering.reverse();
		it=ordering.sortedCopy(data).iterator();
	}
	else
	{
		it=data.iterator();
	}
	if(filterPredicate!=null) it = Iterators.filter(it, filterPredicate);
	if(first>0) Iterators.advance(it, (int)first);
	return count>=0?Iterators.limit(it, (int)count):it;
}
 
Example 7
Source File: OrderedResultIterator.java    From phoenix with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Builds a comparator from the list of columns in ORDER BY clause.
 * @param orderByExpressions the columns in ORDER BY clause.
 * @return the comparator built from the list of columns in ORDER BY clause.
 */
// ImmutableBytesWritable.Comparator doesn't implement generics
@SuppressWarnings("unchecked")
private static Comparator<ResultEntry> buildComparator(List<OrderByExpression> orderByExpressions) {
    Ordering<ResultEntry> ordering = null;
    int pos = 0;
    for (OrderByExpression col : orderByExpressions) {
        Ordering<ImmutableBytesWritable> o = Ordering.from(new ImmutableBytesWritable.Comparator());
        if(!col.isAscending()) o = o.reverse();
        o = col.isNullsLast() ? o.nullsLast() : o.nullsFirst();
        Ordering<ResultEntry> entryOrdering = o.onResultOf(new NthKey(pos++));
        ordering = ordering == null ? entryOrdering : ordering.compound(entryOrdering);
    }
    return ordering;
}
 
Example 8
Source File: UpdateFactory.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override
public Update newUpdate(IJobUpdateInstructions instructions, boolean rollingForward) {
  requireNonNull(instructions);
  IJobUpdateSettings settings = instructions.getSettings();

  checkArgument(
      settings.getMinWaitInInstanceRunningMs() >= 0,
      "Min wait in running must be non-negative.");

  if (settings.getUpdateStrategy().isSetBatchStrategy()) {
    checkArgument(
        settings.getUpdateStrategy().getBatchStrategy().getGroupSize() > 0,
        GROUP_SIZES_INVALID);
  } else if (settings.getUpdateStrategy().isSetVarBatchStrategy()) {
    checkArgument(
        settings.getUpdateStrategy().
            getVarBatchStrategy().
            getGroupSizes().
            stream().
            reduce(0, Integer::sum) > 0,
        GROUP_SIZES_INVALID);

  } else {
    checkArgument(
        settings.getUpdateStrategy().getQueueStrategy().getGroupSize() > 0,
        GROUP_SIZES_INVALID);
  }

  Set<Integer> currentInstances = expandInstanceIds(instructions.getInitialState());
  Set<Integer> desiredInstances = instructions.isSetDesiredState()
      ? expandInstanceIds(ImmutableSet.of(instructions.getDesiredState()))
      : ImmutableSet.of();

  Set<Integer> instances = ImmutableSet.copyOf(Sets.union(currentInstances, desiredInstances));

  ImmutableMap.Builder<Integer, StateEvaluator<Optional<IScheduledTask>>> evaluators =
      ImmutableMap.builder();
  for (int instanceId : instances) {
    Optional<ITaskConfig> desiredStateConfig;
    if (rollingForward) {
      desiredStateConfig = desiredInstances.contains(instanceId)
          ? Optional.of(instructions.getDesiredState().getTask())
          : Optional.empty();
    } else {
      desiredStateConfig = getConfig(instanceId, instructions.getInitialState());
    }

    evaluators.put(
        instanceId,
        new InstanceUpdater(
            desiredStateConfig,
            settings.getMaxPerInstanceFailures(),
            Amount.of((long) settings.getMinWaitInInstanceRunningMs(), Time.MILLISECONDS),
            clock));
  }

  Ordering<Integer> updateOrdering = new UpdateOrdering(currentInstances, desiredInstances);
  Ordering<Integer> updateOrder = rollingForward
      ? updateOrdering
      : updateOrdering.reverse();

  UpdateStrategy<Integer> strategy;

  // Note: Verification that the update strategy exists and is valid has already taken
  // place when the scheduler receives the thrift call.
  // TODO(rdelvalle): Consider combining Batch Update and Variable Batch update strategies.
  if (settings.getUpdateStrategy().isSetBatchStrategy()) {
    strategy = new BatchStrategy<>(
        updateOrder,
        settings.getUpdateStrategy().getBatchStrategy().getGroupSize());
  } else if (settings.getUpdateStrategy().isSetVarBatchStrategy()) {
    strategy = new VariableBatchStrategy<>(
        updateOrder,
        settings.getUpdateStrategy().getVarBatchStrategy().getGroupSizes(),
        rollingForward);
  } else {
    strategy = new QueueStrategy<>(
        updateOrder,
        settings.getUpdateStrategy().getQueueStrategy().getGroupSize());
  }

  JobUpdateStatus successStatus =
      rollingForward ? JobUpdateStatus.ROLLED_FORWARD : JobUpdateStatus.ROLLED_BACK;
  JobUpdateStatus failureStatus = rollingForward && settings.isRollbackOnFailure()
      ? JobUpdateStatus.ROLLING_BACK
      : JobUpdateStatus.FAILED;

  return new Update(
      new OneWayJobUpdater<>(
          strategy,
          settings.getMaxFailedInstances(),
          evaluators.build()),
      successStatus,
      failureStatus);
}
 
Example 9
Source File: TestingHelpers.java    From crate with Apache License 2.0 4 votes vote down vote up
public static <T, K extends Comparable> Matcher<Iterable<? extends T>> isSortedBy(final Function<T, K> extractSortingKeyFunction,
                                                                                  final boolean descending,
                                                                                  @Nullable final Boolean nullsFirst) {
    Ordering<K> ordering = Ordering.natural();
    if (descending) {
        ordering = ordering.reverse();
    }
    if (nullsFirst != null && nullsFirst) {
        ordering = ordering.nullsFirst();
    } else {
        ordering = ordering.nullsLast();
    }
    final Ordering<K> ord = ordering;

    return new TypeSafeDiagnosingMatcher<Iterable<? extends T>>() {
        @Override
        protected boolean matchesSafely(Iterable<? extends T> item, Description mismatchDescription) {
            K previous = null;
            int i = 0;
            for (T elem : item) {
                K current = extractSortingKeyFunction.apply(elem);
                if (previous != null) {
                    if (ord.compare(previous, current) > 0) {
                        mismatchDescription
                            .appendText("element ").appendValue(current)
                            .appendText(" at position ").appendValue(i)
                            .appendText(" is ")
                            .appendText(descending ? "bigger" : "smaller")
                            .appendText(" than previous element ")
                            .appendValue(previous);
                        return false;
                    }
                }
                i++;
                previous = current;
            }
            return true;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("expected iterable to be sorted ");
            if (descending) {
                description.appendText("in DESCENDING order");
            } else {
                description.appendText("in ASCENDING order");
            }
        }
    };
}