org.apache.commons.collections4.ComparatorUtils Java Examples

The following examples show how to use org.apache.commons.collections4.ComparatorUtils. 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: MultiOrderByQueryTests.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
private ArrayList<Document> sort(ArrayList<Document> documents, ArrayList<CompositePath> compositeIndex,
        boolean invert) {
    Collection<Comparator<Document>> comparators = new ArrayList<Comparator<Document>>();
    Iterator<CompositePath> compositeIndexIterator = compositeIndex.iterator();
    while (compositeIndexIterator.hasNext()) {
        CompositePath compositePath = compositeIndexIterator.next();
        CompositePathSortOrder order = compositePath.getOrder();
        if (invert) {
            if (order == CompositePathSortOrder.Descending) {
                order = CompositePathSortOrder.Ascending;
            } else {
                order = CompositePathSortOrder.Descending;
            }
        }
        String path = compositePath.getPath().replace("/", "");
        comparators.add(new CustomComparator(path, order));
    }
    Collections.sort(documents, ComparatorUtils.chainedComparator(comparators));
    return documents;
}
 
Example #2
Source File: AbstractMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
protected static Comparator<ArtifactMetadata> getArtifactMetadataComparator(final QueryParameter queryParameter, String defaultAttr) {
    List<Comparator<ArtifactMetadata>> compList = new ArrayList<>();
    List<String> sortFields = new ArrayList<>();
    if (queryParameter.getSortFields().size() == 0) {
        sortFields.add(defaultAttr);
    } else {
        sortFields = queryParameter.getSortFields();
    }
    for (String attribute : sortFields) {
        switch (attribute) {
            case "id":
                compList.add(Comparator.comparing(ArtifactMetadata::getId));
                break;
            case "whenGathered":
                compList.add(Comparator.comparing(ArtifactMetadata::getWhenGathered));
                break;
            case "fileLastModified":
                compList.add(Comparator.comparing(ArtifactMetadata::getFileLastModified));
            case "version":
                compList.add(Comparator.comparing(ArtifactMetadata::getVersion));
                break;
            case "projectVersion":
                compList.add(Comparator.comparing(ArtifactMetadata::getProjectVersion));
                break;
            case "project":
                compList.add(Comparator.comparing(ArtifactMetadata::getProject));
                break;
            default:
                //
        }
    }
    Comparator<ArtifactMetadata> comp = ComparatorUtils.chainedComparator(compList);
    if (queryParameter.isAscending()) {
        return comp;
    } else {
        return comp.reversed();
    }
}
 
Example #3
Source File: SelectRejectedPredicateTest.java    From feilong-core with Apache License 2.0 5 votes vote down vote up
/**
 * Test select rejected predicate.
 */
@Test
public void testSelectRejectedPredicate(){
    Predicate<Integer> predicate = new ComparatorPredicate<Integer>(10, ComparatorUtils.<Integer> naturalComparator(), Criterion.LESS);

    List<Integer> result = CollectionsUtil.selectRejected(toList(1, 5, 10, 30, 55, 88, 1, 12, 3), predicate);
    assertThat(result, contains(1, 5, 10, 1, 3));
}
 
Example #4
Source File: SelectPredicateTest.java    From feilong-core with Apache License 2.0 5 votes vote down vote up
/**
 * Test select predicate.
 */
@Test
public void testSelectPredicate(){
    //查询 >10 的元素
    Predicate<Integer> predicate = new ComparatorPredicate<Integer>(10, ComparatorUtils.<Integer> naturalComparator(), Criterion.LESS);

    List<Integer> result = CollectionsUtil.select(toList(1, 5, 10, 30, 55, 88, 1, 12, 3), predicate);
    assertThat(result, contains(30, 55, 88, 12));
}
 
Example #5
Source File: ComparatorPredicateComparatorTest.java    From feilong-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testComparatorPredicate1(){
    User user = new User(2L);
    assertEquals(
                    false,
                    BeanPredicateUtil.comparatorPredicate("id", 5L, ComparatorUtils.<Long> naturalComparator(), Criterion.LESS)
                                    .evaluate(user));
}
 
Example #6
Source File: PropertyNameAndValueConvertToClassAndComparatorTest.java    From feilong-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyComparatorWithTreeSetWithComparable(){
    UserSameHashCodeWithComparable userSameHashCodeWithComparable1 = new UserSameHashCodeWithComparable(1, "11");
    UserSameHashCodeWithComparable userSameHashCodeWithComparable2 = new UserSameHashCodeWithComparable(5, "2");
    //------

    PropertyComparator<UserSameHashCodeWithComparable> propertyComparator = new PropertyComparator<>("name");
    assertThat(propertyComparator.compare(userSameHashCodeWithComparable1, userSameHashCodeWithComparable2), lessThan(0));

    propertyComparator = new PropertyComparator<>("name", Integer.class, ComparatorUtils.NATURAL_COMPARATOR);
    assertEquals(1, propertyComparator.compare(userSameHashCodeWithComparable1, userSameHashCodeWithComparable2));
}
 
Example #7
Source File: SortArrayComparatorsTest.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
/**
 * Test sort array null array.
 */
@Test
public void testSortArrayNullArray(){
    String[] arrays = null;
    assertEquals(EMPTY_STRING_ARRAY, sortArray(arrays, ComparatorUtils.<String> naturalComparator()));
}
 
Example #8
Source File: BeanQuery.java    From bean-query with Apache License 2.0 4 votes vote down vote up
/**
 * Using an array of Comparators, applied in sequence until one returns not equal or the array is exhausted.
 */
public BeanQuery<T> orderBy(Comparator... beanComparator) {
  this.comparator = new DelegatedSortOrderableComparator(ComparatorUtils.chainedComparator(beanComparator));
  return this;
}
 
Example #9
Source File: PropertyNameAndValueConvertToClassAndComparatorTest.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testPropertyComparatorBlankPropertyNameAndPropertyValueConvertToClassAndNaturalComparator(){
    new PropertyComparator<>("    ", Integer.class, ComparatorUtils.NATURAL_COMPARATOR);
}
 
Example #10
Source File: PropertyNameAndValueConvertToClassAndComparatorTest.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testPropertyComparatorEmptyPropertyNameAndPropertyValueConvertToClassAndNaturalComparator(){
    new PropertyComparator<>("", Integer.class, ComparatorUtils.NATURAL_COMPARATOR);
}
 
Example #11
Source File: PropertyNameAndValueConvertToClassAndComparatorTest.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
@Test(expected = NullPointerException.class)
public void testPropertyComparatorNullPropertyNameAndPropertyValueConvertToClassAndNaturalComparator(){
    new PropertyComparator<>(null, Integer.class, ComparatorUtils.NATURAL_COMPARATOR);
}
 
Example #12
Source File: PropertyNameAndComparatorTest.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testPropertyComparatorBlankPropertyNameAndNaturalComparator(){
    new PropertyComparator<>("    ", ComparatorUtils.NATURAL_COMPARATOR);
}
 
Example #13
Source File: PropertyNameAndComparatorTest.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testPropertyComparatorEmptyPropertyNameAndNaturalComparator(){
    new PropertyComparator<>("", ComparatorUtils.NATURAL_COMPARATOR);
}
 
Example #14
Source File: PropertyNameAndComparatorTest.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
@Test(expected = NullPointerException.class)
public void testPropertyComparatorNullPropertyNameAndNaturalComparator(){
    new PropertyComparator<>(null, ComparatorUtils.NATURAL_COMPARATOR);
}
 
Example #15
Source File: ComparatorPredicateComparatorTest.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
/**
 * Test equal predicate blank property name.
 */
@Test(expected = IllegalArgumentException.class)
public void testComparatorPredicateBlankPropertyName(){
    BeanPredicateUtil.comparatorPredicate("", 5, ComparatorUtils.<Integer> naturalComparator(), Criterion.LESS);
}
 
Example #16
Source File: ComparatorPredicateComparatorTest.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
/**
 * Test equal predicate empty property name.
 */
@Test(expected = IllegalArgumentException.class)
public void testComparatorPredicateEmptyPropertyName(){
    BeanPredicateUtil.comparatorPredicate("", 5, ComparatorUtils.<Integer> naturalComparator(), Criterion.LESS);
}
 
Example #17
Source File: ComparatorPredicateComparatorTest.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
/**
 * Test equal predicate null property name.
 */
@Test(expected = NullPointerException.class)
public void testComparatorPredicateNullPropertyName(){
    BeanPredicateUtil.comparatorPredicate((String) null, 5, ComparatorUtils.<Integer> naturalComparator(), Criterion.LESS);
}
 
Example #18
Source File: ConsistencyWriter.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
private Single<Boolean> waitForWriteBarrierAsync(RxDocumentServiceRequest barrierRequest, long selectedGlobalCommittedLsn) {
    AtomicInteger writeBarrierRetryCount = new AtomicInteger(ConsistencyWriter.MAX_NUMBER_OF_WRITE_BARRIER_READ_RETRIES);
    AtomicLong maxGlobalCommittedLsnReceived = new AtomicLong(0);
    return Observable.defer(() -> {
        if (barrierRequest.requestContext.timeoutHelper.isElapsed()) {
            return Observable.error(new RequestTimeoutException());
        }

        Single<List<StoreResult>> storeResultListObs = this.storeReader.readMultipleReplicaAsync(
                barrierRequest,
                true /*allowPrimary*/,
                1 /*any replica with correct globalCommittedLsn is good enough*/,
                false /*requiresValidLsn*/,
                false /*useSessionToken*/,
                ReadMode.Strong,
                false /*checkMinLsn*/,
                false /*forceReadAll*/);
        return storeResultListObs.toObservable().flatMap(
                responses -> {
                    if (responses != null && responses.stream().anyMatch(response -> response.globalCommittedLSN >= selectedGlobalCommittedLsn)) {
                        return Observable.just(Boolean.TRUE);
                    }

                    //get max global committed lsn from current batch of responses, then update if greater than max of all batches.
                    long maxGlobalCommittedLsn = (responses != null) ?
                        (Long) responses.stream().map(s -> s.globalCommittedLSN).max(ComparatorUtils.NATURAL_COMPARATOR).orElse(0L) :
                        0L;

                    maxGlobalCommittedLsnReceived.set(maxGlobalCommittedLsnReceived.get() > maxGlobalCommittedLsn ?
                                                              maxGlobalCommittedLsnReceived.get() : maxGlobalCommittedLsn);

                    //only refresh on first barrier call, set to false for subsequent attempts.
                    barrierRequest.requestContext.forceRefreshAddressCache = false;

                    //get max global committed lsn from current batch of responses, then update if greater than max of all batches.
                    if (writeBarrierRetryCount.getAndDecrement() == 0) {
                        logger.debug("ConsistencyWriter: WaitForWriteBarrierAsync - Last barrier multi-region strong. Responses: {}",
                                     String.join("; ", responses.stream().map(r -> r.toString()).collect(Collectors.toList())));
                        logger.debug("ConsistencyWriter: Highest global committed lsn received for write barrier call is {}", maxGlobalCommittedLsnReceived);
                        return Observable.just(false);
                    }

                    return Observable.empty();
                });
    }).repeatWhen(s -> s.flatMap(x -> {
            // repeat with a delay
            if ((ConsistencyWriter.MAX_NUMBER_OF_WRITE_BARRIER_READ_RETRIES - writeBarrierRetryCount.get()) > ConsistencyWriter.MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION) {
                return Observable.timer(ConsistencyWriter.DELAY_BETWEEN_WRITE_BARRIER_CALLS_IN_MS, TimeUnit.MILLISECONDS);
            } else {
                return Observable.timer(ConsistencyWriter.SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION, TimeUnit.MILLISECONDS);
            }
    })
    ).take(1).toSingle();
}
 
Example #19
Source File: BeanComparatorUtil.java    From feilong-core with Apache License 2.0 3 votes vote down vote up
/**
 * 按照不同指定属性 <code>propertyNameAndOrders</code> 排序的 {@link Comparator}.
 *
 * @param <T>
 *            the generic type
 * @param propertyNameAndOrders
 *            属性名称和排序因子,
 * 
 *            <p>
 *            格式可以是纯的属性名称, 比如 "name"; 也可以是属性名称+排序因子(以空格分隔),比如 "name desc"
 *            </p>
 * 
 *            <h3>说明:</h3>
 *            <blockquote>
 * 
 *            <dl>
 *            <dt>关于属性名称</dt>
 *            <dd>
 *            泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be
 *            modified,参见<a href="../../bean/BeanUtil.html#propertyName">propertyName</a>,<br>
 *            该属性对应的value 必须实现 {@link Comparable}接口.
 *            </dd>
 * 
 *            <dt>关于排序因子</dt>
 *            <dd>
 *            可以没有排序因子<br>
 *            如果有,值可以是asc(顺序),desc(倒序)两种;<br>
 *            如果没有,默认按照asc(顺序)排序;<br>
 *            此外,asc/desc忽略大小写
 *            </dd>
 * 
 *            </dl>
 * 
 *            </blockquote>
 * @return 如果propertyNameAndOrders是单值,那么直接调用 {@link #propertyComparator(String)} 返回
 * @throws NullPointerException
 *             如果 <code>propertyNameAndOrders</code> 是null,<br>
 *             或者有元素是 null;
 * @throws IllegalArgumentException
 *             如果 <code>propertyNameAndOrders</code> 是empty,<br>
 *             或者有元素是 blank
 * @see org.apache.commons.collections4.ComparatorUtils#chainedComparator(java.util.Collection)
 * @since 1.10.2 support propertyNameAndOrder
 */
public static <T> Comparator<T> chainedComparator(String...propertyNameAndOrders){
    Validate.notEmpty(propertyNameAndOrders, "propertyNameAndOrders can't be null/empty!");

    //如果propertyNameAndOrders是单值,那么直接调用 com.feilong.core.util.comparator.BeanComparatorUtil.propertyComparator(String) 返回
    if (1 == propertyNameAndOrders.length){
        return propertyComparator(propertyNameAndOrders[0]);
    }

    //---------------------------------------------------------------

    List<Comparator<T>> comparators = newArrayList();
    for (String propertyNameAndOrder : propertyNameAndOrders){
        Validate.notBlank(propertyNameAndOrder, "propertyNameAndOrder can't be blank!");

        String[] propertyNameAndOrderArray = SortHelper.parsePropertyNameAndOrder(propertyNameAndOrder);

        //注意:此处不要使用 propertyComparator(propertyName)

        //因为,PropertyComparator 如果属性值相同,会使用其他规则继续比较(为了TreeMap/treeSet), 
        //也就是说,通常而言一次就比较出顺序,后续的propertyNameAndOrders 就没作用了
        Comparator instance = ComparatorUtils.nullHighComparator(ComparableComparator.comparableComparator()); //null排在最后面  

        BeanComparator<T> beanComparator = new BeanComparator<>(propertyNameAndOrderArray[0], instance);
        comparators.add(isAsc(propertyNameAndOrderArray) ? beanComparator : reversedComparator(beanComparator));
    }
    return ComparatorUtils.chainedComparator(comparators);
}
 
Example #20
Source File: SortUtil.java    From feilong-core with Apache License 2.0 2 votes vote down vote up
/**
 * 如果 <code>comparators length ==1</code>,返回 comparators[0]; 否则返回 {@link ComparatorUtils#chainedComparator(Comparator...)};
 *
 * @param <O>
 *            the generic type
 * @param comparators
 *            the comparators
 * @return the comparator
 * @since 1.8.2
 */
@SafeVarargs
private static <O> Comparator<O> toComparator(Comparator<O>...comparators){
    return 1 == comparators.length ? comparators[0] : ComparatorUtils.chainedComparator(comparators);
}