Example usage for java.util Collections reverseOrder

List of usage examples for java.util Collections reverseOrder

Introduction

In this page you can find the example usage for java.util Collections reverseOrder.

Prototype

@SuppressWarnings("unchecked")
public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) 

Source Link

Document

Returns a comparator that imposes the reverse ordering of the specified comparator.

Usage

From source file:org.pentaho.reporting.designer.core.util.table.expressions.ReportPreProcessorPropertiesTableModel.java

/**
 * @noinspection unchecked/*from  ww w . jav a2  s  .  c  om*/
 */
protected void updateData(final ReportPreProcessor elements) throws IntrospectionException {
    this.elements = elements;
    if (elements == null) {
        this.editors = null;
    } else {
        this.editors = new BeanUtility(elements);
    }

    final ReportPreProcessorPropertyMetaData[] metaData = selectCommonAttributes();
    if (tableStyle == TableStyle.ASCENDING) {
        Arrays.sort(metaData, new PlainMetaDataComparator());
        this.groupings = new GroupingHeader[metaData.length];
        this.metaData = metaData;
    } else if (tableStyle == TableStyle.DESCENDING) {
        Arrays.sort(metaData, Collections.reverseOrder(new PlainMetaDataComparator()));
        this.groupings = new GroupingHeader[metaData.length];
        this.metaData = metaData;
    } else {
        Arrays.sort(metaData, new GroupedMetaDataComparator());

        int groupCount = 0;
        final Locale locale = Locale.getDefault();
        if (metaData.length > 0) {
            String oldValue = null;

            for (int i = 0; i < metaData.length; i++) {
                if (groupCount == 0) {
                    groupCount = 1;
                    final ReportPreProcessorPropertyMetaData firstdata = metaData[i];
                    oldValue = firstdata.getGrouping(locale);
                    continue;
                }

                final ReportPreProcessorPropertyMetaData data = metaData[i];
                final String grouping = data.getGrouping(locale);
                if ((ObjectUtilities.equal(oldValue, grouping)) == false) {
                    oldValue = grouping;
                    groupCount += 1;
                }
            }
        }

        final ReportPreProcessorPropertyMetaData[] groupedMetaData = new ReportPreProcessorPropertyMetaData[metaData.length
                + groupCount];
        this.groupings = new GroupingHeader[groupedMetaData.length];
        int targetIdx = 0;
        GroupingHeader group = null;
        for (int sourceIdx = 0; sourceIdx < metaData.length; sourceIdx++) {
            final ReportPreProcessorPropertyMetaData data = metaData[sourceIdx];
            if (sourceIdx == 0) {
                group = new GroupingHeader(data.getGrouping(locale));
                groupings[targetIdx] = group;
                targetIdx += 1;
            } else {
                final String newgroup = data.getGrouping(locale);
                if ((ObjectUtilities.equal(newgroup, group.getHeaderText())) == false) {
                    group = new GroupingHeader(newgroup);
                    groupings[targetIdx] = group;
                    targetIdx += 1;
                }
            }

            groupings[targetIdx] = group;
            groupedMetaData[targetIdx] = data;
            targetIdx += 1;
        }

        this.metaData = groupedMetaData;
    }

    fireTableDataChanged();
}

From source file:org.springframework.web.socket.sockjs.AbstractSockJsService.java

/**
 * Use this property to configure one or more prefixes that this SockJS service is
 * allowed to serve. The prefix (e.g. "/echo") is needed to extract the SockJS
 * specific portion of the URL (e.g. "${prefix}/info", "${prefix}/iframe.html", etc).
 * <p>/* ww  w . j a  va  2  s .c  o  m*/
 * This property is not strictly required. In most cases, the SockJS path can be
 * auto-detected since the initial request from the SockJS client is of the form
 * "{prefix}/info". Assuming the SockJS service is mapped correctly (e.g. using
 * Ant-style pattern "/echo/**") this should work fine. This property can be used
 * to configure explicitly the prefixes this service is allowed to service.
 *
 * @param prefixes the prefixes to use; prefixes do not need to include the portions
 *        of the path that represent Servlet container context or Servlet path.
 */
public void setValidSockJsPrefixes(String... prefixes) {

    this.validSockJsPrefixes.clear();
    for (String prefix : prefixes) {
        if (prefix.endsWith("/") && (prefix.length() > 1)) {
            prefix = prefix.substring(0, prefix.length() - 1);
        }
        this.validSockJsPrefixes.add(prefix);
    }

    // sort with longest prefix at the top
    Collections.sort(this.validSockJsPrefixes, Collections.reverseOrder(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return new Integer(o1.length()).compareTo(new Integer(o2.length()));
        }
    }));
}

From source file:business.controllers.RequestController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/requests", method = RequestMethod.GET)
public List<RequestListRepresentation> getRequestList(UserAuthenticationToken user) {
    log.info("GET /requests (for user: " + (user == null ? "null" : user.getId()) + ")");

    List<RequestListRepresentation> result = new ArrayList<RequestListRepresentation>();

    Date start = new Date();
    List<HistoricProcessInstance> processInstances = requestService.getProcessInstancesForUser(user.getUser());
    for (HistoricProcessInstance instance : processInstances) {
        RequestListRepresentation request = new RequestListRepresentation();
        requestFormService.transferData(instance, request, user.getUser());
        result.add(request);/*from  w w  w.  j  ava 2  s .  c o  m*/
    }
    Date endQ = new Date();
    log.info("GET: fetching took " + (endQ.getTime() - start.getTime()) + " ms.");
    if (user.getUser().isRequester()) {
        Collections.sort(result, Collections.reverseOrder(requestListRepresentationStartTimeComparator));
        Date endSort = new Date();
        log.info("GET: sorting took " + (endSort.getTime() - endQ.getTime()) + " ms.");
    } else if (user.getUser().isScientificCouncilMember()) {
        Collections.sort(result, Collections.reverseOrder(requestListRepresentationComparator));
        Date endSort = new Date();
        log.info("GET: sorting took " + (endSort.getTime() - endQ.getTime()) + " ms.");
    } else {
        Collections.sort(result, Collections.reverseOrder(requestListRepresentationComparator));
        Date endSort = new Date();
        log.info("GET: sorting took " + (endSort.getTime() - endQ.getTime()) + " ms.");
    }
    return result;
}

From source file:org.apache.falcon.resource.extensions.ExtensionManager.java

@GET
@Path("list/{extension-name}")
@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_JSON })
public ExtensionJobList getExtensionJobs(@PathParam("extension-name") String extensionName,
        @DefaultValue("") @QueryParam("fields") String fields,
        @DefaultValue(ASCENDING_SORT_ORDER) @QueryParam("sortOrder") String sortOrder,
        @DefaultValue("0") @QueryParam("offset") Integer offset,
        @QueryParam("numResults") Integer resultsPerPage,
        @DefaultValue("") @QueryParam("doAs") String doAsUser) {
    checkIfExtensionServiceIsEnabled();/*from  ww  w. j  a v  a 2 s  .c  o  m*/
    resultsPerPage = resultsPerPage == null ? getDefaultResultsPerPage() : resultsPerPage;
    try {
        // get filtered entities
        List<Entity> entities = getEntityList("", "", "", TAG_PREFIX_EXTENSION_NAME + extensionName, "",
                doAsUser);
        if (entities.isEmpty()) {
            return new ExtensionJobList(0);
        }

        // group entities by extension job name
        Map<String, List<Entity>> groupedEntities = groupEntitiesByJob(entities);

        // sort by extension job name
        List<String> jobNames = new ArrayList<>(groupedEntities.keySet());
        switch (sortOrder.toLowerCase()) {
        case DESCENDING_SORT_ORDER:
            Collections.sort(jobNames, Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER));
            break;
        default:
            Collections.sort(jobNames, String.CASE_INSENSITIVE_ORDER);
        }

        // pagination and format output
        int pageCount = getRequiredNumberOfResults(jobNames.size(), offset, resultsPerPage);
        HashSet<String> fieldSet = new HashSet<>(Arrays.asList(fields.toUpperCase().split(",")));
        ExtensionJobList jobList = new ExtensionJobList(pageCount);
        for (int i = offset; i < offset + pageCount; i++) {
            String jobName = jobNames.get(i);
            List<Entity> jobEntities = groupedEntities.get(jobName);
            EntityList entityList = new EntityList(buildEntityElements(fieldSet, jobEntities),
                    jobEntities.size());
            jobList.addJob(new ExtensionJobList.JobElement(jobName, entityList));
        }
        return jobList;
    } catch (FalconException | IOException e) {
        LOG.error("Failed to get extension job list of " + extensionName + ": ", e);
        throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.jasig.portlet.notice.util.sort.Sorting.java

/**
 * @deprecated Part of the legacy, Portlet-based API.
 *//*from w  w w  .j  av  a2s  .c o m*/
@Deprecated
private static Comparator<NotificationEntry> chooseConfiguredComparator(PortletRequest req) {

    final PortletPreferences prefs = req.getPreferences();
    final String strategyName = prefs.getValue(SORT_STRATEGY_PREFERENCE, null);
    if (strategyName == null) {
        // No strategy means "natural" ordering;  we won't be sorting...
        return null;
    }

    // We WILL be sorting;  work out the details...
    try {
        final SortStrategy strategy = SortStrategy.valueOf(strategyName.toUpperCase()); // tolerant of case mismatch
        final String orderName = req.getParameter(SORT_ORDER_PARAMETER_NAME);
        final SortOrder order = StringUtils.isNotBlank(orderName) ? SortOrder.valueOf(orderName.toUpperCase()) // tolerant of case mismatch
                : SortOrder.valueOf(SORT_ORDER_DEFAULT);

        return order.equals(SortOrder.ASCENDING) ? strategy.getComparator() // Default/ascending order
                : Collections.reverseOrder(strategy.getComparator()); // Descending order
    } catch (IllegalArgumentException e) {
        LOGGER.warn("Unable to sort based on parameters {}='{}' and {}='{}'", SORT_STRATEGY_PARAMETER_NAME,
                strategyName, SORT_ORDER_PARAMETER_NAME, req.getParameter(SORT_ORDER_PARAMETER_NAME));
    }

    // We didn't succeed in selecting a strategy & order
    return null;

}

From source file:org.jfrog.hudson.ArtifactoryServer.java

public List<String> getSnapshotRepositoryKeysFirst(DeployerOverrider deployerOverrider, Item item) {
    CredentialsConfig credentialsConfig = CredentialManager.getPreferredDeployer(deployerOverrider, this);
    List<String> repositoryKeys = getLocalRepositoryKeys(credentialsConfig.getCredentials(item));
    if (repositoryKeys == null || repositoryKeys.isEmpty()) {
        return Lists.newArrayList();
    }/*  w w  w. j a  v  a  2s.c  o  m*/
    Collections.sort(repositoryKeys, Collections.reverseOrder(new RepositoryComparator()));
    return repositoryKeys;
}

From source file:org.alfresco.repo.blog.cannedqueries.GetBlogPostsCannedQuery.java

@Override
protected List<BlogEntity> queryAndFilter(CannedQueryParameters parameters) {
    Long start = (logger.isDebugEnabled() ? System.currentTimeMillis() : null);

    Object paramBeanObj = parameters.getParameterBean();
    if (paramBeanObj == null)
        throw new NullPointerException("Null GetBlogPosts query params");

    GetBlogPostsCannedQueryParams paramBean = (GetBlogPostsCannedQueryParams) paramBeanObj;
    String requestedCreator = paramBean.getCmCreator();
    boolean isPublished = paramBean.getIsPublished();
    Date publishedFromDate = paramBean.getPublishedFromDate();
    Date publishedToDate = paramBean.getPublishedToDate();

    // note: refer to SQL for specific DB filtering (eg.parent node and optionally blog integration aspect, etc)
    List<BlogEntity> results = cannedQueryDAO.executeQuery(QUERY_NAMESPACE, QUERY_SELECT_GET_BLOGS, paramBean,
            0, Integer.MAX_VALUE);

    List<BlogEntity> filtered = new ArrayList<BlogEntity>(results.size());
    for (BlogEntity result : results) {
        boolean nextNodeIsAcceptable = true;

        Date actualPublishedDate = DefaultTypeConverter.INSTANCE.convert(Date.class, result.getPublishedDate());

        // Only return blog-posts whose cm:published status matches that requested (ie. a blog "is published" when published date is not null)
        boolean blogIsPublished = (actualPublishedDate != null);
        if (blogIsPublished != isPublished) {
            nextNodeIsAcceptable = false;
        }/* www . j  a v  a2  s .  co  m*/

        // Only return blog posts whose creator matches the given username, if there is one.
        if (requestedCreator != null) {
            AuditablePropertiesEntity auditProps = result.getNode().getAuditableProperties();
            if ((auditProps == null) || (!requestedCreator.equals(auditProps.getAuditCreator()))) {
                nextNodeIsAcceptable = false;
            }
        }

        // Only return blogs published within the specified dates
        if ((publishedFromDate != null) || (publishedToDate != null)) {
            if (actualPublishedDate != null) {
                if (publishedFromDate != null && actualPublishedDate.before(publishedFromDate)) {
                    nextNodeIsAcceptable = false;
                }
                if (publishedToDate != null && actualPublishedDate.after(publishedToDate)) {
                    nextNodeIsAcceptable = false;
                }
            } else {
                nextNodeIsAcceptable = false;
            }
        }

        if (nextNodeIsAcceptable) {
            filtered.add(result);
        }
    }

    List<Pair<? extends Object, SortOrder>> sortPairs = parameters.getSortDetails().getSortPairs();

    // For now, the BlogService only sorts by a single property.
    if (sortPairs != null && !sortPairs.isEmpty()) {
        Pair<? extends Object, SortOrder> sortPair = sortPairs.get(0);

        QName sortProperty = (QName) sortPair.getFirst();
        Comparator<BlogEntity> comparator = new BlogEntityComparator(sortProperty);

        if (sortPair.getSecond() == SortOrder.DESCENDING) {
            comparator = Collections.reverseOrder(comparator);
        }
        Collections.sort(filtered, comparator);
    }

    if (start != null) {
        logger.debug(
                "Base query: " + filtered.size() + " in " + (System.currentTimeMillis() - start) + " msecs");
    }

    return filtered;
}

From source file:org.pentaho.reporting.designer.core.editor.styles.SimpleStyleTableModel.java

protected SimpleStyleDataBackend updateData(final ElementStyleSheet styleSheet) {
    final StyleMetaData[] metaData = selectCommonAttributes();
    final TableStyle tableStyle = getTableStyle();
    if (tableStyle == TableStyle.ASCENDING) {
        Arrays.sort(metaData, new PlainMetaDataComparator());
        return (new SimpleStyleDataBackend(metaData, new GroupingHeader[metaData.length], styleSheet));
    } else if (tableStyle == TableStyle.DESCENDING) {
        Arrays.sort(metaData, Collections.reverseOrder(new PlainMetaDataComparator()));
        return (new SimpleStyleDataBackend(metaData, new GroupingHeader[metaData.length], styleSheet));
    } else {//  w w  w . j  a v a 2s  . c om
        Arrays.sort(metaData, new GroupedMetaDataComparator());
        final Locale locale = Locale.getDefault();
        int groupCount = 0;
        int metaDataCount = 0;
        if (metaData.length > 0) {
            String oldValue = null;

            for (int i = 0; i < metaData.length; i++) {
                final StyleMetaData data = metaData[i];
                if (data.isHidden()) {
                    continue;
                }
                if (!WorkspaceSettings.getInstance().isVisible(data)) {
                    continue;
                }

                metaDataCount += 1;

                if (groupCount == 0) {
                    groupCount = 1;
                    oldValue = data.getGrouping(locale);
                    continue;
                }

                final String grouping = data.getGrouping(locale);
                if ((ObjectUtilities.equal(oldValue, grouping)) == false) {
                    groupCount += 1;
                    oldValue = grouping;
                    continue;
                }
            }
        }

        final StyleMetaData[] groupedMetaData = new StyleMetaData[metaDataCount + groupCount];
        int targetIdx = 0;
        GroupingHeader[] groupings = new GroupingHeader[groupedMetaData.length];
        GroupingHeader group = null;
        for (int sourceIdx = 0; sourceIdx < metaData.length; sourceIdx++) {
            final StyleMetaData data = metaData[sourceIdx];
            if (data.isHidden()) {
                continue;
            }
            if (!WorkspaceSettings.getInstance().isVisible(data)) {
                continue;
            }

            if (targetIdx == 0) {
                group = new GroupingHeader(data.getGrouping(locale));
                groupings[targetIdx] = group;
                targetIdx += 1;
            } else {
                final String newgroup = data.getGrouping(locale);
                if ((ObjectUtilities.equal(newgroup, group.getHeaderText())) == false) {
                    group = new GroupingHeader(newgroup);
                    groupings[targetIdx] = group;
                    targetIdx += 1;
                }
            }

            groupings[targetIdx] = group;
            groupedMetaData[targetIdx] = data;

            targetIdx += 1;
        }

        if (oldDataBackend != null) {
            groupings = reconcileState(groupings, oldDataBackend.getGroupings());
        }

        return new SimpleStyleDataBackend(groupedMetaData, groupings, styleSheet);
    }
}

From source file:org.alfresco.repo.blog.cannedqueries.DraftsAndPublishedBlogPostsCannedQuery.java

@Override
protected List<BlogEntity> queryAndFilter(CannedQueryParameters parameters) {
    Long start = (logger.isDebugEnabled() ? System.currentTimeMillis() : null);

    Object paramBeanObj = parameters.getParameterBean();
    if (paramBeanObj == null)
        throw new NullPointerException("Null GetBlogPosts query params");

    DraftsAndPublishedBlogPostsCannedQueryParams paramBean = (DraftsAndPublishedBlogPostsCannedQueryParams) paramBeanObj;
    String requestedCreator = paramBean.getCmCreator();
    Date createdFromDate = paramBean.getCreatedFromDate();
    Date createdToDate = paramBean.getCreatedToDate();

    // note: refer to SQL for specific DB filtering (eg.parent node and optionally blog integration aspect, etc)
    List<BlogEntity> results = cannedQueryDAO.executeQuery(QUERY_NAMESPACE, QUERY_SELECT_GET_BLOGS, paramBean,
            0, Integer.MAX_VALUE);

    List<BlogEntity> filtered = new ArrayList<BlogEntity>(results.size());
    for (BlogEntity result : results) {
        // Is this next node in the list to be included in the results?
        boolean nextNodeIsAcceptable = true;

        Date actualPublishedDate = DefaultTypeConverter.INSTANCE.convert(Date.class, result.getPublishedDate());

        String actualCreator = result.getCreator();
        Date actualCreatedDate = DefaultTypeConverter.INSTANCE.convert(Date.class, result.getCreatedDate());

        // Return all published Blog Posts
        if (actualPublishedDate != null) {
            // Intentionally empty
        } else {//  w  w w  .  ja  v  a2 s  .  c o m
            // We're relying on cm:published being null below i.e. we are dealing with draft blog posts.
            if (requestedCreator != null) {
                if (!requestedCreator.equals(actualCreator)) {
                    nextNodeIsAcceptable = false;
                }
            } else {
                nextNodeIsAcceptable = false;
            }
        }

        // Only return blogs created within the specified dates
        if ((createdFromDate != null) || (createdToDate != null)) {
            if (actualCreatedDate != null) {
                if (createdFromDate != null && actualCreatedDate.before(createdFromDate)) {
                    nextNodeIsAcceptable = false;
                }
                if (createdToDate != null && actualCreatedDate.after(createdToDate)) {
                    nextNodeIsAcceptable = false;
                }
            }
        }

        if (nextNodeIsAcceptable) {
            filtered.add(result);
        }
    }

    List<Pair<? extends Object, SortOrder>> sortPairs = parameters.getSortDetails().getSortPairs();
    if (sortPairs != null && !sortPairs.isEmpty()) {
        for (Pair<? extends Object, SortOrder> sortPair : sortPairs) {
            QName sortProperty = (QName) sortPair.getFirst();
            Comparator<BlogEntity> comparator = new BlogEntityComparator(sortProperty);

            if (sortPair.getSecond() == SortOrder.DESCENDING) {
                comparator = Collections.reverseOrder(comparator);
            }
            Collections.sort(filtered, comparator);
        }
    }

    if (start != null) {
        logger.debug(
                "Base query: " + filtered.size() + " in " + (System.currentTimeMillis() - start) + " msecs");
    }

    return filtered;
}

From source file:net.sourceforge.fenixedu.domain.candidacyProcess.erasmus.ApprovedLearningAgreementDocumentFile.java

protected List<ApprovedLearningAgreementExecutedAction> getSentEmailAcceptedStudentActions() {
    List<ApprovedLearningAgreementExecutedAction> executedActionList = new ArrayList<ApprovedLearningAgreementExecutedAction>();

    CollectionUtils.select(getExecutedActionsSet(), new Predicate() {

        @Override/*from   ww  w  .j  a va 2  s.  c om*/
        public boolean evaluate(Object arg0) {
            return ((ApprovedLearningAgreementExecutedAction) arg0).isSentEmailAcceptedStudent();
        };

    }, executedActionList);

    Collections.sort(executedActionList, Collections.reverseOrder(ExecutedAction.WHEN_OCCURED_COMPARATOR));

    return executedActionList;
}