Example usage for org.apache.commons.collections ComparatorUtils reversedComparator

List of usage examples for org.apache.commons.collections ComparatorUtils reversedComparator

Introduction

In this page you can find the example usage for org.apache.commons.collections ComparatorUtils reversedComparator.

Prototype

public static Comparator reversedComparator(Comparator comparator) 

Source Link

Document

Gets a comparator that reverses the order of the given comparator.

Usage

From source file:mondrian.olap.fun.PartialSortTest.java

@SuppressWarnings({ "unchecked" })
private void doPartialSort(Object[] items, boolean descending, int limit) {
    Comparator<Object> comp = ComparatorUtils.naturalComparator();
    if (descending) {
        comp = ComparatorUtils.reversedComparator(comp);
    }/*from  w  w  w .ja  v  a2 s.  c om*/
    FunUtil.partialSort(items, comp, limit);
}

From source file:com.ineunet.knife.core.query.QueryParamParser.java

/**
 * Create a Comparator by <code>orderBy</code> and <code>sort</code>.
 *//*from  w  w  w .j av a  2 s  . com*/
@SuppressWarnings("unchecked")
public <X> Comparator<X> getComparator() {
    parse();
    if (StringUtils.isBlank(orderByField))
        return ComparatorUtils.NATURAL_COMPARATOR;
    Comparator<X> mycmp = ComparableComparator.getInstance();
    if ("DESC".equalsIgnoreCase(sort)) {
        mycmp = ComparatorUtils.reversedComparator(mycmp);
    }
    return new BeanComparator(orderByField, mycmp);
}

From source file:module.mission.presentationTier.action.MissionOrganizationAction.java

public ActionForward showDelegationsForAuthorization(final HttpServletRequest request,
        final Accountability accountability) {
    String sortBy = request.getParameter("sortBy");
    String order = request.getParameter("order");
    request.setAttribute("sortBy", (sortBy == null) ? "parentUnitName" : sortBy);
    request.setAttribute("order", (order == null) ? "asc" : order);
    request.setAttribute("accountability", accountability);

    Comparator<FunctionDelegation> comparator;
    if (StringUtils.equals(sortBy, "childPartyName")) {
        comparator = FunctionDelegation.COMPARATOR_BY_DELEGATEE_CHILD_PARTY_NAME;
    } else {/*from w  ww.j ava2s.  co m*/
        comparator = FunctionDelegation.COMPARATOR_BY_DELEGATEE_PARENT_UNIT_NAME;
    }
    if (StringUtils.equals(order, "desc")) {
        comparator = ComparatorUtils.reversedComparator(comparator);
    }
    TreeSet<FunctionDelegation> functionDelegationDelegated = new TreeSet<FunctionDelegation>(comparator);
    functionDelegationDelegated.addAll(accountability.getFunctionDelegationDelegated());
    request.setAttribute("functionDelegationDelegated", functionDelegationDelegated);

    return forward("/mission/showDelegationForAuthorization.jsp");
}

From source file:info.jtrac.hibernate.HibernateJtracDao.java

private void doInMemorySort(List<Item> list, ItemSearch itemSearch) {
    // we should never come here if search is across multiple spaces
    final Field field = itemSearch.getSpace().getMetadata().getField(itemSearch.getSortFieldName());
    final ArrayList<String> valueList = new ArrayList<String>(field.getOptions().keySet());
    Comparator<Item> comp = new Comparator<Item>() {
        public int compare(Item left, Item right) {
            Object leftVal = left.getValue(field.getName());
            String leftValString = leftVal == null ? null : leftVal.toString();
            int leftInd = valueList.indexOf(leftValString);
            Object rightVal = right.getValue(field.getName());
            String rightValString = rightVal == null ? null : rightVal.toString();
            int rightInd = valueList.indexOf(rightValString);
            return leftInd - rightInd;
        }//from   w ww . ja  v  a  2s. c om
    };
    Collections.sort(list, itemSearch.isSortDescending() ? ComparatorUtils.reversedComparator(comp) : comp);
}

From source file:br.com.ingenieux.mojo.beanstalk.AbstractBeanstalkMojo.java

protected String lookupSolutionStack(final String solutionStack) {
    if (!hasWildcards(solutionStack)) {
        return solutionStack;
    }//  w w  w .  ja v  a  2  s . co  m

    getLog().info("Looking up for solution stacks matching '" + solutionStack + "'");

    final Function<SolutionStackDescription, String> stackTransformer = new Function<SolutionStackDescription, String>() {
        @Override
        public String apply(SolutionStackDescription input) {
            return input.getSolutionStackName();
        }
    };
    final List<SolutionStackDescription> stackDetails = getService().listAvailableSolutionStacks()
            .getSolutionStackDetails();

    Collection<String> solStackList = Collections2.transform(stackDetails, stackTransformer);

    final Pattern stackPattern = globify(solutionStack);

    List<String> matchingStacks = new ArrayList<String>(
            Collections2.filter(solStackList, new Predicate<String>() {
                @Override
                public boolean apply(String input) {
                    return stackPattern.matcher(input).matches();
                }
            }));

    Collections.sort(matchingStacks, ComparatorUtils.reversedComparator(Collator.getInstance()));

    if (matchingStacks.isEmpty()) {
        throw new IllegalStateException("unable to lookup a solution stack matching '" + solutionStack + "'");
    }

    return matchingStacks.iterator().next();
}

From source file:info.jtrac.repository.HibernateJtracDao.java

private void doInMemorySort(List<Item> list, ItemSearch itemSearch) {
    // we should never come here if search is across multiple spaces
    final Field field = itemSearch.getSpace().getMetadata().getField(itemSearch.getSortFieldName());
    final ArrayList<String> valueList = new ArrayList<String>(field.getOptions().keySet());
    Comparator<Item> comp = new Comparator<Item>() {
        @Override//from w ww  .j ava2s. co m
        public int compare(Item left, Item right) {
            Object leftVal = left.getValue(field.getName());
            String leftValString = leftVal == null ? null : leftVal.toString();
            int leftInd = valueList.indexOf(leftValString);
            Object rightVal = right.getValue(field.getName());
            String rightValString = rightVal == null ? null : rightVal.toString();
            int rightInd = valueList.indexOf(rightValString);
            return leftInd - rightInd;
        }
    };
    @SuppressWarnings("unchecked")
    Comparator<Item> comparator = itemSearch.isSortDescending()
            ? (Comparator<Item>) ComparatorUtils.reversedComparator(comp)
            : comp;
    Collections.sort(list, comparator);
}

From source file:org.jaulp.wicket.data.provider.SortCollectionUtils.java

/**
 * Sort.//  w  w  w  .  jav  a  2 s  .  c o m
 *
 * @param <T>
 *            the generic type of the list
 * @param list
 *            the list
 * @param property
 *            the property
 * @param ascending
 *            the ascending
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> void sortList(List<T> list, String property, boolean ascending) {
    Comparator comparator = new BeanComparator(property, new ComparableComparator());
    if (ascending) {
        comparator = ComparatorUtils.reversedComparator(comparator);
    }
    Collections.sort(list, comparator);
}

From source file:org.kuali.rice.kew.rule.service.impl.RuleServiceImpl.java

public void removeRuleInvolvement(Id entityToBeRemoved, List<Long> ruleIds, Long documentId)
        throws WorkflowException {
    KimPrincipal principal = null;//from  w  w  w .  ja v a2 s . c  o m
    Group workgroupToRemove = null;
    if (entityToBeRemoved instanceof UserId) {
        principal = KEWServiceLocator.getIdentityHelperService().getPrincipal(((UserId) entityToBeRemoved));
    } else if (entityToBeRemoved instanceof GroupId) {
        workgroupToRemove = KEWServiceLocator.getIdentityHelperService().getGroup((GroupId) entityToBeRemoved);
    } else {
        throw new WorkflowRuntimeException(
                "Invalid ID for entity to be replaced was passed, type was: " + entityToBeRemoved);
    }
    List<RuleBaseValues> existingRules = loadRules(ruleIds);
    // sort the rules so that delegations are last, very important in order to deal with parent-child versioning properly
    Collections.sort(existingRules, ComparatorUtils.reversedComparator(new RuleDelegationSorter()));
    // we maintain the old-new mapping so we can associate versioned delegate rules with their appropriate re-versioned parents when applicable
    Map<Long, RuleBaseValues> oldIdNewRuleMapping = new HashMap<Long, RuleBaseValues>();
    Map<Long, RuleBaseValues> rulesToVersion = new HashMap<Long, RuleBaseValues>();
    for (RuleBaseValues existingRule : existingRules) {
        if (!shouldChangeRuleInvolvement(documentId, existingRule)) {
            continue;
        }
        List<RuleResponsibility> finalResponsibilities = new ArrayList<RuleResponsibility>();
        RuleVersion ruleVersion = createNewRemoveReplaceVersion(existingRule, oldIdNewRuleMapping, documentId);
        boolean modified = false;
        for (RuleResponsibility responsibility : (List<RuleResponsibility>) ruleVersion.rule
                .getResponsibilities()) {
            if (responsibility.isUsingWorkflowUser()) {
                if (principal != null
                        && responsibility.getRuleResponsibilityName().equals(principal.getPrincipalName())) {
                    modified = true;
                    continue;
                }
            } else if (responsibility.isUsingGroup()) {
                if (workgroupToRemove != null
                        && responsibility.getRuleResponsibilityName().equals(workgroupToRemove.getGroupId())) {
                    modified = true;
                    continue;
                }
            }
            finalResponsibilities.add(responsibility);
        }
        if (modified) {
            // if this is a delegation rule, we need to hook it up to the parent rule
            if (ruleVersion.parent != null && ruleVersion.delegation != null) {
                hookUpDelegateRuleToParentRule(ruleVersion.parent, ruleVersion.rule, ruleVersion.delegation);
            }
            if (finalResponsibilities.isEmpty()) {
                // deactivate the rule instead
                ruleVersion.rule.setActiveInd(false);
            } else {
                ruleVersion.rule.setResponsibilities(finalResponsibilities);
            }
            try {
                save2(ruleVersion.rule, ruleVersion.delegation, false);
                if (ruleVersion.delegation != null) {
                    KEWServiceLocator.getRuleDelegationService().save(ruleVersion.delegation);
                }
                rulesToVersion.put(ruleVersion.rule.getRuleBaseValuesId(), ruleVersion.rule);
                if (ruleVersion.parent != null) {
                    save2(ruleVersion.parent, null, false);
                    rulesToVersion.put(ruleVersion.parent.getRuleBaseValuesId(), ruleVersion.parent);
                }
            } catch (Exception e) {
                throw new WorkflowRuntimeException(e);
            }
        }
    }
    makeCurrent2(new ArrayList<RuleBaseValues>(rulesToVersion.values()));
}

From source file:org.kuali.rice.kew.rule.service.impl.RuleServiceImpl.java

public void replaceRuleInvolvement(Id entityToBeReplaced, Id newEntity, List<Long> ruleIds, Long documentId)
        throws WorkflowException {
    KimPrincipal principalToBeReplaced = null;
    Group workgroupToReplace = null;
    if (entityToBeReplaced instanceof UserId) {
        principalToBeReplaced = KEWServiceLocator.getIdentityHelperService()
                .getPrincipal(((UserId) entityToBeReplaced));
    } else if (entityToBeReplaced instanceof GroupId) {
        workgroupToReplace = KEWServiceLocator.getIdentityHelperService()
                .getGroup((GroupId) entityToBeReplaced);
    } else {/*from  w w w .  ja va  2s.  c o m*/
        throw new WorkflowRuntimeException(
                "Invalid ID for entity to be replaced was passed, type was: " + entityToBeReplaced);
    }
    KimPrincipal newPrincipal = null;
    Group newWorkgroup = null;
    if (newEntity instanceof UserId) {
        newPrincipal = KEWServiceLocator.getIdentityHelperService().getPrincipal((UserId) newEntity);
    } else if (newEntity instanceof GroupId) {
        newWorkgroup = KEWServiceLocator.getIdentityHelperService().getGroup((GroupId) newEntity);
    }
    List<RuleBaseValues> existingRules = loadRules(ruleIds);
    // sort the rules so that delegations are last, very important in order to deal with parent-child versioning properly
    Collections.sort(existingRules, ComparatorUtils.reversedComparator(new RuleDelegationSorter()));
    // we maintain the old-new mapping so we can associate versioned delegate rules with their appropriate re-versioned parents when applicable
    Map<Long, RuleBaseValues> oldIdNewRuleMapping = new HashMap<Long, RuleBaseValues>();
    Map<Long, RuleBaseValues> rulesToVersion = new HashMap<Long, RuleBaseValues>();
    for (RuleBaseValues existingRule : existingRules) {
        if (!shouldChangeRuleInvolvement(documentId, existingRule)) {
            continue;
        }
        RuleVersion ruleVersion = createNewRemoveReplaceVersion(existingRule, oldIdNewRuleMapping, documentId);
        RuleBaseValues rule = ruleVersion.rule;
        boolean modified = false;
        for (RuleResponsibility responsibility : (List<RuleResponsibility>) rule.getResponsibilities()) {
            if (responsibility.isUsingWorkflowUser()) {
                if (principalToBeReplaced != null && responsibility.getRuleResponsibilityName()
                        .equals(principalToBeReplaced.getPrincipalId())) {
                    if (newPrincipal != null) {
                        responsibility.setRuleResponsibilityType(KEWConstants.RULE_RESPONSIBILITY_WORKFLOW_ID);
                        responsibility.setRuleResponsibilityName(newPrincipal.getPrincipalId());
                        modified = true;
                    } else if (newWorkgroup != null) {
                        responsibility.setRuleResponsibilityType(KEWConstants.RULE_RESPONSIBILITY_GROUP_ID);
                        responsibility.setRuleResponsibilityName(newWorkgroup.getGroupId());
                        modified = true;
                    }
                }
            } else if (responsibility.isUsingGroup()) {
                if (workgroupToReplace != null
                        && responsibility.getRuleResponsibilityName().equals(workgroupToReplace.getGroupId())) {
                    if (newPrincipal != null) {
                        responsibility.setRuleResponsibilityType(KEWConstants.RULE_RESPONSIBILITY_WORKFLOW_ID);
                        responsibility.setRuleResponsibilityName(newPrincipal.getPrincipalId());
                        modified = true;
                    } else if (newWorkgroup != null) {
                        responsibility.setRuleResponsibilityType(KEWConstants.RULE_RESPONSIBILITY_GROUP_ID);
                        responsibility.setRuleResponsibilityName(newWorkgroup.getGroupId().toString());
                        modified = true;
                    }
                }
            }
        }
        if (modified) {
            try {
                // if this is a delegation rule, we need to hook it up to the parent rule
                if (ruleVersion.parent != null && ruleVersion.delegation != null) {
                    hookUpDelegateRuleToParentRule(ruleVersion.parent, ruleVersion.rule,
                            ruleVersion.delegation);
                }
                save2(ruleVersion.rule, ruleVersion.delegation, false);
                if (ruleVersion.delegation != null) {
                    KEWServiceLocator.getRuleDelegationService().save(ruleVersion.delegation);
                }
                rulesToVersion.put(ruleVersion.rule.getRuleBaseValuesId(), ruleVersion.rule);
                if (ruleVersion.parent != null) {
                    save2(ruleVersion.parent, null, false);
                    rulesToVersion.put(ruleVersion.parent.getRuleBaseValuesId(), ruleVersion.parent);
                }
            } catch (Exception e) {
                throw new WorkflowRuntimeException(e);
            }
        }
    }

    makeCurrent2(new ArrayList<RuleBaseValues>(rulesToVersion.values()));

}

From source file:org.omnaest.utils.beans.replicator.BeanReplicatorWithCollectionsTest.java

@SuppressWarnings("unchecked")
@Test/*from w  w w  .  j a v a 2 s  .  c o m*/
public void testMappingOfVariousCollectionTypes() {
    TestSimpleBean testSimpleBean = new TestSimpleBean();
    {
        Map<String, Object> map = MapUtils.builder().<String, Object>put("key1", "value1").put("key2", "value2")
                .buildAs().linkedHashMap();
        testSimpleBean.setMap(map);
        testSimpleBean.setSortedMap(MapUtils.builder().putAll(map).buildAs()
                .treeMap(ComparatorUtils.reversedComparator(ComparatorUtils.NATURAL_COMPARATOR)));
        testSimpleBean.setSet(SetUtils.valueOf("a", "b", "c", "d"));
        testSimpleBean.setSortedSet(new TreeSet<String>(SetUtils.valueOf("b", "c", "d", "a")));
        testSimpleBean.setList(ListUtils.valueOf(new SubBean("a", "b"), new SubBean("c", "d")));
        testSimpleBean.setCollection(ListUtils.valueOf("a", "b", "c", "d"));
        testSimpleBean.setIterable(ListUtils.valueOf("a", "b", "c", "d"));
        testSimpleBean.setArray(new String[] { "a", "b", "c", "d" });
    }

    BeanCopier<TestSimpleBean> beanCopier = new BeanCopier<TestSimpleBean>(TestSimpleBean.class);
    TestSimpleBean clone = beanCopier.clone(testSimpleBean);

    assertNotNull(clone);

    assertEquals(testSimpleBean.getMap(), clone.getMap());
    assertNotSame(testSimpleBean.getMap(), clone.getMap());

    assertEquals(testSimpleBean.getSortedMap(), clone.getSortedMap());
    assertNotSame(testSimpleBean.getSortedMap(), clone.getSortedMap());

    assertEquals(testSimpleBean.getSet(), clone.getSet());
    assertNotSame(testSimpleBean.getSet(), clone.getSet());

    assertEquals(testSimpleBean.getSortedSet(), clone.getSortedSet());
    assertNotSame(testSimpleBean.getSortedSet(), clone.getSortedSet());

    assertEquals(testSimpleBean.getList(), clone.getList());
    assertNotSame(testSimpleBean.getList(), clone.getList());

    assertEquals(testSimpleBean.getCollection(), clone.getCollection());
    assertNotSame(testSimpleBean.getCollection(), clone.getCollection());

    assertEquals(testSimpleBean.getIterable(), clone.getIterable());
    assertNotSame(testSimpleBean.getIterable(), clone.getIterable());

    assertArrayEquals(testSimpleBean.getArray(), clone.getArray());
    assertNotSame(testSimpleBean.getArray(), clone.getArray());
}