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:no.sesat.search.mode.command.NavigatableESPFastCommand.java

private void collectModifier(final String navigatorKey, final IQueryResult result,
        final FastSearchResult<ResultItem> searchResult) {

    final Navigator nav = navigatedTo.get(navigatorKey);
    final INavigator navigator = null != result ? result.getNavigator(nav.getName()) : null;

    if (navigator != null) {

        final Iterator modifers = navigator.modifiers();

        while (modifers.hasNext()) {

            final IModifier modifier = (IModifier) modifers.next();
            searchResult.addModifier(navigatorKey, new Modifier(modifier.getName(), modifier.getCount(), nav));
        }/*from w  w w . j  a  v  a2s .c o m*/

        if (searchResult.getModifiers(navigatorKey) != null) {
            switch (nav.getSort()) {
            case DAY_MONTH_YEAR:
                Collections.sort(searchResult.getModifiers(navigatorKey),
                        ModifierDateComparator.DAY_MONTH_YEAR);
                break;
            case DAY_MONTH_YEAR_DESCENDING:
                Collections.sort(searchResult.getModifiers(navigatorKey),
                        ModifierDateComparator.DAY_MONTH_YEAR_DESCENDING);
                break;
            case YEAR_MONTH_DAY_DESCENDING:
                Collections.sort(searchResult.getModifiers(navigatorKey),
                        ModifierDateComparator.YEAR_MONTH_DAY_DESCENDING);
                break;
            case YEAR:
                Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR);
                break;
            case MONTH_YEAR:
                Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.MONTH_YEAR);
                break;
            case YEAR_MONTH:
                Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR_MONTH);
                break;
            case ALPHABETICAL:
                Collections.sort(searchResult.getModifiers(navigatorKey),
                        ModifierStringComparator.ALPHABETICAL);
                break;
            case ALPHABETICAL_DESCENDING:
                Collections.sort(searchResult.getModifiers(navigatorKey),
                        Collections.reverseOrder(ModifierStringComparator.ALPHABETICAL));
                break;
            case CUSTOM:
                Collections.sort(searchResult.getModifiers(navigatorKey), getModifierComparator(nav));
                break;
            case NONE:
                // Use the soting the index returns
                break;
            case COUNT:
                /* Fall through */
            default:
                Collections.sort(searchResult.getModifiers(navigatorKey));
                break;
            }
        }

    } else if (nav.getChildNavigator() != null) {
        navigatedTo.put(navigatorKey, nav.getChildNavigator());
        collectModifier(navigatorKey, result, searchResult);
    }
}

From source file:org.yes.cart.web.page.component.customer.order.CustomerOrderPanel.java

private List<CustomerOrder> getValidCustomerOrderInChronologicalOrder(final Customer customer,
        final Date date) {

    // all in DB//ww  w .j av a2 s .  c o  m
    final List<CustomerOrder> orders = customerOrderService.findCustomerOrders(customer, date);

    // remove temporary orders
    final Iterator<CustomerOrder> ordersIt = orders.iterator();
    while (ordersIt.hasNext()) {
        final CustomerOrder order = ordersIt.next();
        if (CustomerOrder.ORDER_STATUS_NONE.equals(order.getOrderStatus())) {
            ordersIt.remove();
        }
    }

    // sort
    Collections.sort(orders, Collections.reverseOrder(new CustomerOrderComparator()));

    return orders;
}

From source file:de.whs.poodle.controllers.instructor.FeedbackOverviewController.java

public Comparator<FeedbackOverviewRowData> getRowComparator(FeedbackOverviewDataTablesRequest dataTablesRequest,
        AbstractHelper helper) {/*from   www .  j a v a  2s.com*/
    Comparator<FeedbackOverviewRowData> comparator;

    // compare by students
    if (dataTablesRequest.isOrderByStudent()) {
        comparator = (r1, r2) -> r1.getStudent().getId() - r2.getStudent().getId();
    } else { // compare by exercise
        int exerciseRootId = dataTablesRequest.getOrderByExerciseRootId();

        comparator = (r1, r2) -> {
            // note that each of these may be null if the student has not completed the exercise
            Statistic s1 = r1.getExerciseRootIdToStatisticMap().get(exerciseRootId);
            Statistic s2 = r2.getExerciseRootIdToStatisticMap().get(exerciseRootId);

            return helper.getOrderValue(s1) - helper.getOrderValue(s2);
        };
    }

    // if we have to sort descending, reverse the comparator
    if (dataTablesRequest.getOrderDirection() == OrderDirection.DESC)
        comparator = Collections.reverseOrder(comparator);

    return comparator;
}

From source file:edu.emory.cci.aiw.cvrg.eureka.common.entity.JobEntity.java

/**
 * Gets job events sorted in reverse order of occurrence. Uses the
 * {@link JobEventComparator} to perform sorting.
 *
 * @return a {@link List} of {@link JobEventEntity}s in reverse order of
 * occurrence./*from   w  ww . j a  va  2s  .  c  o  m*/
 */
public List<JobEventEntity> getJobEventsInReverseOrder() {
    List<JobEventEntity> jobEvents = new ArrayList<>(this.jobEvents);
    Collections.sort(jobEvents, Collections.reverseOrder(JOB_EVENT_ENTITY_COMPARATOR));
    return jobEvents;
}

From source file:org.nuxeo.ecm.platform.relations.web.listener.ejb.RelationActionsBean.java

@Override
@Factory(value = "currentDocumentIncomingRelations", scope = ScopeType.EVENT)
public List<StatementInfo> getIncomingStatementsInfo() {
    if (incomingStatementsInfo != null) {
        return incomingStatementsInfo;
    }/*from   w w w  .  ja va2 s  .c om*/
    DocumentModel currentDoc = getCurrentDocument();
    Resource docResource = getDocumentResource(currentDoc);
    if (docResource == null) {
        incomingStatements = Collections.emptyList();
        incomingStatementsInfo = Collections.emptyList();
    } else {
        Graph graph = relationManager.getGraphByName(RelationConstants.GRAPH_NAME);
        incomingStatements = graph.getStatements(null, null, docResource);
        if (graph instanceof JenaGraph) {
            // add old statements, BBB
            Resource oldDocResource = getOldDocumentResource(currentDoc);
            incomingStatements.addAll(graph.getStatements(null, null, oldDocResource));
        }
        incomingStatementsInfo = getStatementsInfo(incomingStatements);
        // sort by modification date, reverse
        Comparator<StatementInfo> comp = Collections.reverseOrder(new StatementInfoComparator());
        Collections.sort(incomingStatementsInfo, comp);
    }
    return incomingStatementsInfo;
}

From source file:org.theospi.portfolio.presentation.control.ListPresentationController.java

/** Sort given collection of presentations, using given sortColumn in ascending or descending order
 **//from   w w w  .  j av  a  2s  .  co m
 **/
private void sortPresentations(final Collection<Presentation> presentations, final String sortColumn,
        final Boolean inAscendingOrder) {
    Comparator<Presentation> comparator = sortName2PresentationComparator.get(sortColumn);

    if (comparator != null) {
        if (!inAscendingOrder) {
            comparator = Collections.reverseOrder(comparator);
        }
        Collections.sort((List) presentations, comparator);
    } else {
        logger.error("no comparator defined for column " + sortColumn);
    }
}

From source file:contestTabulation.Setup.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    Entity contestInfo = Retrieve.contestInfo();

    GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
            .setTransport(httpTransport)
            .setClientSecrets((String) contestInfo.getProperty("OAuth2ClientId"),
                    (String) contestInfo.getProperty("OAuth2ClientSecret"))
            .build().setFromTokenResponse(new JacksonFactory().fromString(
                    ((Text) contestInfo.getProperty("OAuth2Token")).getValue(), GoogleTokenResponse.class));

    String docName = null, docLevel = null;
    for (Level level : Level.values()) {
        docName = req.getParameter("doc" + level.getName());
        if (docName != null) {
            docLevel = level.toString();
            break;
        }/* w  ww  . j  av a 2s .co  m*/
    }

    if (docLevel == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Spreadsheet creation request must have paramater document name parameter set");
        return;
    }

    Query query = new Query("registration")
            .setFilter(new FilterPredicate("schoolLevel", FilterOperator.EQUAL, docLevel))
            .addSort("schoolName", SortDirection.ASCENDING);
    List<Entity> registrations = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());

    Map<String, List<JSONObject>> studentData = new HashMap<String, List<JSONObject>>();
    for (Entity registration : registrations) {
        String regSchoolName = ((String) registration.getProperty("schoolName")).trim();
        String regStudentDataJSON = unescapeHtml4(((Text) registration.getProperty("studentData")).getValue());

        JSONArray regStudentData = null;
        try {
            regStudentData = new JSONArray(regStudentDataJSON);
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }

        for (int i = 0; i < regStudentData.length(); i++) {
            if (!studentData.containsKey(regSchoolName)) {
                studentData.put(regSchoolName, new ArrayList<JSONObject>());
            }
            try {
                studentData.get(regSchoolName).add(regStudentData.getJSONObject(i));
            } catch (JSONException e) {
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                e.printStackTrace();
                return;
            }
        }
    }

    for (List<JSONObject> students : studentData.values()) {
        Collections.sort(students, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject a, JSONObject b) {
                try {
                    return a.getString("name").compareTo(b.getString("name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }

    Workbook workbook = new XSSFWorkbook();

    XSSFCellStyle boldStyle = (XSSFCellStyle) workbook.createCellStyle();
    Font boldFont = workbook.createFont();
    boldFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    boldStyle.setFont(boldFont);

    Map<Subject, XSSFCellStyle> subjectCellStyles = new HashMap<Subject, XSSFCellStyle>();
    for (Subject subject : Subject.values()) {
        final double ALPHA = .144;
        String colorStr = (String) contestInfo.getProperty("color" + subject.getName());
        byte[] backgroundColor = new byte[] { Integer.valueOf(colorStr.substring(1, 3), 16).byteValue(),
                Integer.valueOf(colorStr.substring(3, 5), 16).byteValue(),
                Integer.valueOf(colorStr.substring(5, 7), 16).byteValue() };
        // http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
        byte[] borderColor = new byte[] { (byte) ((backgroundColor[0] & 0xff) * (1 - ALPHA)),
                (byte) ((backgroundColor[1] & 0xff) * (1 - ALPHA)),
                (byte) ((backgroundColor[2] & 0xff) * (1 - ALPHA)) };

        XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
        style.setFillBackgroundColor(new XSSFColor(backgroundColor));
        style.setFillPattern(CellStyle.ALIGN_FILL);

        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(new XSSFColor(borderColor));
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(new XSSFColor(borderColor));
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(new XSSFColor(borderColor));
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(new XSSFColor(borderColor));
        subjectCellStyles.put(subject, style);
    }

    Entry<String, List<JSONObject>>[] studentDataEntries = studentData.entrySet().toArray(new Entry[] {});
    Arrays.sort(studentDataEntries, Collections.reverseOrder(new Comparator<Entry<String, List<JSONObject>>>() {
        @Override
        public int compare(Entry<String, List<JSONObject>> arg0, Entry<String, List<JSONObject>> arg1) {
            return Integer.compare(arg0.getValue().size(), arg1.getValue().size());
        }
    }));

    for (Entry<String, List<JSONObject>> studentDataEntry : studentDataEntries) {
        Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(studentDataEntry.getKey()));
        Row row = sheet.createRow((short) 0);

        String[] columnNames = { "Name", "Grade", "N", "C", "M", "S" };
        for (int i = 0; i < columnNames.length; i++) {
            String columnName = columnNames[i];
            Cell cell = row.createCell(i);
            cell.setCellValue(columnName);
            cell.setCellStyle(boldStyle);
            CellUtil.setAlignment(cell, workbook, CellStyle.ALIGN_CENTER);
        }

        int longestNameLength = 7;
        int rowNum = 1;
        for (JSONObject student : studentDataEntry.getValue()) {
            try {
                row = sheet.createRow((short) rowNum);
                row.createCell(0).setCellValue(student.getString("name"));
                row.createCell(1).setCellValue(student.getInt("grade"));

                for (Subject subject : Subject.values()) {
                    String value = student.getBoolean(subject.toString()) ? "" : "X";
                    Cell cell = row.createCell(Arrays.asList(columnNames).indexOf(subject.toString()));
                    cell.setCellValue(value);
                    cell.setCellStyle(subjectCellStyles.get(subject));
                }

                if (student.getString("name").length() > longestNameLength) {
                    longestNameLength = student.getString("name").length();
                }

                rowNum++;
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            }
        }

        sheet.createFreezePane(0, 1, 0, 1);
        // sheet.autoSizeColumn((short) 0); Not supported by App Engine
        sheet.setColumnWidth((short) 0, (int) (256 * longestNameLength * 1.1));
    }

    Drive drive = new Drive.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName("contestTabulation").build();

    File body = new File();
    body.setTitle(docName);
    body.setMimeType("application/vnd.google-apps.spreadsheet");

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    workbook.write(outStream);
    ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
    InputStreamContent content = new InputStreamContent(
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", inStream);

    drive.files().insert(body, content).execute();
    workbook.close();
}

From source file:com.attribyte.essem.ESUserStore.java

/**
 * Gets all tagged graphs for a user./*ww w.j a  va2  s. co m*/
 * @param index The index.
 * @param uid The user id.
 * @param tags A collection of tags.
 * @param start The start index.
 * @param limit The maximum returned.
 * @return The list of graphs.
 * @throws IOException on retrieve error.
 */
public List<StoredGraph> getUserGraphs(final String index, final String uid, final Collection<String> tags,
        final int start, final int limit) throws IOException {

    String indexName = index + SUFFIX;

    try {
        URI indexURI = new URI(esEndpoint.uri.getScheme(), esEndpoint.uri.getUserInfo(),
                esEndpoint.uri.getHost(), esEndpoint.uri.getPort(), "/" + indexName + "/_search", null, null);
        Request esRequest = esEndpoint.postRequestBuilder(indexURI, StoredGraphQuery
                .buildUserGraphsRequest(uid, tags, start, limit).toJSON().getBytes(Charsets.UTF_8)).create();
        Response esResponse = httpClient.send(esRequest);

        switch (esResponse.getStatusCode()) {
        case 200:
            ObjectNode keysObject = Util.mapper
                    .readTree(Util.parserFactory.createParser(esResponse.getBody().toByteArray()));
            List<StoredGraph> storedGraphs = StoredGraphParser.parseGraphs(keysObject);
            Map<MetricKey, StoredGraph> recentUserGraphs = recentUserGraphCache.getIfPresent(uid);
            if (start == 0 && recentUserGraphs != null && recentUserGraphs.size() > 0) {
                Set<StoredGraph> combinedGraphs = Sets.newHashSet(storedGraphs);
                combinedGraphs.addAll(recentUserGraphs.values());
                storedGraphs = Lists.newArrayList(combinedGraphs);
                Collections.sort(storedGraphs, Collections.reverseOrder(StoredGraph.createTimeComparator));
                return storedGraphs.size() < limit ? storedGraphs : storedGraphs.subList(0, limit);
            } else {
                return storedGraphs;
            }
        default:
            throw new IOException("Problem selecting user graphs (" + esResponse.getStatusCode() + ")");
        }
    } catch (URISyntaxException use) {
        throw new AssertionError();
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.phd.CommonPhdIndividualProgramProcessDA.java

public ActionForward viewAlertMessages(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/*from   w  ww  .j a  v  a2s  .c o m*/

    TreeSet<PhdAlertMessage> orderedMessages = new TreeSet<PhdAlertMessage>(
            Collections.reverseOrder(PhdAlertMessage.COMPARATOR_BY_WHEN_CREATED_AND_ID));
    orderedMessages.addAll(getLoggedPerson(request).getPhdAlertMessagesSet());
    ArrayList<PhdAlertMessage> lastMessages = new ArrayList<PhdAlertMessage>();
    lastMessages.addAll(orderedMessages);

    request.setAttribute("unread", "false");
    request.setAttribute("alertMessages",
            lastMessages.subList(0, Math.min(lastMessages.size(), NUMBER_OF_LAST_MESSAGES)));
    request.setAttribute("tooManyMessages", (lastMessages.size() > NUMBER_OF_LAST_MESSAGES) ? "true" : "false");
    return mapping.findForward("viewAlertMessages");
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity.FifoIntraQueuePreemptionPlugin.java

/**
 * Algorithm for calculating idealAssigned is as follows:
 * For each partition:/*w  ww. j a va2  s  . c  o  m*/
 *  Q.reassignable = Q.used - Q.selected;
 *  
 * # By default set ideal assigned 0 for app.
 * app.idealAssigned as 0
 * # get user limit from scheduler.
 * userLimitRes = Q.getUserLimit(userName)
 * 
 * # initial all value to 0
 * Map<String, Resource> userToAllocated
 * 
 * # Loop from highest priority to lowest priority app to calculate ideal
 * for app in sorted-by(priority) {
 *  if Q.reassignable < 0:
 *    break;
 *    
 *  if (user-to-allocated.get(app.user) < userLimitRes) {
 *   idealAssigned = min((userLimitRes - userToAllocated.get(app.user)), 
 *                      (app.used + app.pending - app.selected))
 *   app.idealAssigned = min(Q.reassignable, idealAssigned)
 *   userToAllocated.get(app.user) += app.idealAssigned;
 *  } else { 
 *   // skip this app because user-limit reached
 *  }
 *  Q.reassignable -= app.idealAssigned
 * }
 *  
 * @param clusterResource Cluster Resource
 * @param partitionBasedResource resource per partition
 * @param tq TempQueue
 * @param selectedCandidates Already Selected preemption candidates
 * @param queueReassignableResource Resource used in a queue
 * @param orderedByPriority List of running apps
 * @param perUserAMUsed AM used resource
 * @return List of temp apps ordered from low to high priority
 */
private TreeSet<TempAppPerPartition> calculateIdealAssignedResourcePerApp(Resource clusterResource,
        Resource partitionBasedResource, TempQueuePerPartition tq,
        Map<ApplicationAttemptId, Set<RMContainer>> selectedCandidates, Resource queueReassignableResource,
        PriorityQueue<TempAppPerPartition> orderedByPriority, Map<String, Resource> perUserAMUsed) {

    Comparator<TempAppPerPartition> reverseComp = Collections.reverseOrder(new TAPriorityComparator());
    TreeSet<TempAppPerPartition> orderedApps = new TreeSet<>(reverseComp);

    Map<String, Resource> userIdealAssignedMapping = new HashMap<>();
    String partition = tq.partition;

    Map<String, Resource> preCalculatedUserLimit = new HashMap<String, Resource>();

    while (!orderedByPriority.isEmpty()) {
        // Remove app from the next highest remaining priority and process it to
        // calculate idealAssigned per app.
        TempAppPerPartition tmpApp = orderedByPriority.remove();
        orderedApps.add(tmpApp);

        // Once unallocated resource is 0, we can stop assigning ideal per app.
        if (Resources.lessThanOrEqual(rc, clusterResource, queueReassignableResource, Resources.none())) {
            continue;
        }

        String userName = tmpApp.app.getUser();
        Resource userLimitResource = preCalculatedUserLimit.get(userName);

        // Verify whether we already calculated headroom for this user.
        if (userLimitResource == null) {
            userLimitResource = Resources
                    .clone(tq.leafQueue.getUserLimitPerUser(userName, partitionBasedResource, partition));

            Resource amUsed = perUserAMUsed.get(userName);
            if (null == amUsed) {
                amUsed = Resources.createResource(0, 0);
            }

            // Real AM used need not have to be considered for user-limit as well.
            userLimitResource = Resources.subtract(userLimitResource, amUsed);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Userlimit for user '" + userName + "' is :" + userLimitResource + ", and amUsed is:"
                        + amUsed);
            }

            preCalculatedUserLimit.put(userName, userLimitResource);
        }

        Resource idealAssignedForUser = userIdealAssignedMapping.get(userName);

        if (idealAssignedForUser == null) {
            idealAssignedForUser = Resources.createResource(0, 0);
            userIdealAssignedMapping.put(userName, idealAssignedForUser);
        }

        // Calculate total selected container resources from current app.
        getAlreadySelectedPreemptionCandidatesResource(selectedCandidates, tmpApp, partition);

        // For any app, used+pending will give its idealAssigned. However it will
        // be tightly linked to queue's unallocated quota. So lower priority apps
        // idealAssigned may fall to 0 if higher priority apps demand is more.
        Resource appIdealAssigned = Resources.add(tmpApp.getUsedDeductAM(), tmpApp.getPending());
        Resources.subtractFrom(appIdealAssigned, tmpApp.selected);

        if (Resources.lessThan(rc, clusterResource, idealAssignedForUser, userLimitResource)) {
            appIdealAssigned = Resources.min(rc, clusterResource, appIdealAssigned,
                    Resources.subtract(userLimitResource, idealAssignedForUser));
            tmpApp.idealAssigned = Resources
                    .clone(Resources.min(rc, clusterResource, queueReassignableResource, appIdealAssigned));
            Resources.addTo(idealAssignedForUser, tmpApp.idealAssigned);
        } else {
            continue;
        }

        // Also set how much resource is needed by this app from others.
        Resource appUsedExcludedSelected = Resources.subtract(tmpApp.getUsedDeductAM(), tmpApp.selected);
        if (Resources.greaterThan(rc, clusterResource, tmpApp.idealAssigned, appUsedExcludedSelected)) {
            tmpApp.setToBePreemptFromOther(Resources.subtract(tmpApp.idealAssigned, appUsedExcludedSelected));
        }

        Resources.subtractFrom(queueReassignableResource, tmpApp.idealAssigned);
    }

    return orderedApps;
}