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() 

Source Link

Document

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Usage

From source file:org.araqne.pkg.PackageManagerService.java

private PackageVersionHistory selectVersion(String version, PackageMetadata metadata, ProgressMonitor monitor) {
    PackageVersionHistory selected = null;
    if (version == null) {
        ArrayList<PackageVersionHistory> versions = new ArrayList<PackageVersionHistory>();
        versions.addAll(metadata.getVersions());
        Collections.sort(versions, Collections.reverseOrder());
        selected = versions.get(0);/*from   www  . j av  a2s .  com*/
    } else {
        Version v = new Version(version);
        for (PackageVersionHistory h : metadata.getVersions())
            if (h.getVersion().equals(v)) {
                selected = h;
            }
    }

    if (selected != null && monitor != null)
        monitor.writeln("  -> selected version: " + selected.getVersion());

    return selected;
}

From source file:org.springframework.context.support.DefaultLifecycleProcessor.java

private void stopBeans() {
    Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
    Map<Integer, LifecycleGroup> phases = new HashMap<>();
    lifecycleBeans.forEach((beanName, bean) -> {
        int shutdownOrder = getPhase(bean);
        LifecycleGroup group = phases.get(shutdownOrder);
        if (group == null) {
            group = new LifecycleGroup(shutdownOrder, this.timeoutPerShutdownPhase, lifecycleBeans, false);
            phases.put(shutdownOrder, group);
        }//from   w  w  w .j  a  v  a  2s . c o m
        group.add(beanName, bean);
    });
    if (!phases.isEmpty()) {
        List<Integer> keys = new ArrayList<>(phases.keySet());
        keys.sort(Collections.reverseOrder());
        for (Integer key : keys) {
            phases.get(key).stop();
        }
    }
}

From source file:com.liato.bankdroid.banking.banks.SEB.java

@Override
public void updateTransactions(Account account, Urllib urlopen) throws LoginException, BankException {
    super.updateTransactions(account, urlopen);

    //No transaction history for loans, funds and credit cards.
    int accType = account.getType();
    if (accType == Account.LOANS || accType == Account.FUNDS || accType == Account.CCARD)
        return;//w  w w .j a  va2s.  c o m

    Matcher matcher;
    try {
        response = urlopen.open(
                "https://m.seb.se/cgi-bin/pts3/mps/1100/mps1102.aspx?M1=show&P2=1&P4=1&P1=" + account.getId());
        matcher = reTransactions.matcher(response);
        ArrayList<Transaction> transactions = new ArrayList<Transaction>();
        while (matcher.find()) {
            /*
             * Capture groups:
             * GROUP                    EXAMPLE DATA
             * 1: Book. date            101214
             * 2: Transaction           St1
             * 3: Trans. date           10-12-11
             * 4: Amount                -200,07  
             * 
             */
            String date;
            if (matcher.group(3) == null || matcher.group(3).length() == 0) {
                date = Html.fromHtml(matcher.group(1)).toString().trim();
                date = String.format("%s-%s-%s", date.substring(0, 2), date.substring(2, 4),
                        date.substring(4, 6));
            } else {
                date = Html.fromHtml(matcher.group(3)).toString().trim();
            }
            transactions.add(new Transaction("20" + date, Html.fromHtml(matcher.group(2)).toString().trim(),
                    Helpers.parseBalance(matcher.group(4))));
        }
        Collections.sort(transactions, Collections.reverseOrder());
        account.setTransactions(transactions);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.kuali.kra.coi.CoiDisclosure.java

public List<CoiDisclosureNotepad> getCoiDisclosureNotepads() {

    if (this.coiDisclosureNotepads == null) {
        this.coiDisclosureNotepads = new ArrayList<CoiDisclosureNotepad>();
    }/*from ww w. j a  v a2  s.c  o  m*/
    Collections.sort(coiDisclosureNotepads, Collections.reverseOrder());
    return this.coiDisclosureNotepads;
}

From source file:org.jenkinsci.plugins.jenkinsreviewbot.ReviewboardConnection.java

Collection<String> getPendingReviews(long periodInHours, String respository)
        throws IOException, JAXBException, ParseException {
    ensureAuthentication();/*  w  w  w.j av a 2s.  c o  m*/
    ReviewsResponse response = unmarshalResponse(getRequestsUrl(respository), ReviewsResponse.class);
    List<ReviewItem> list = response.requests.array;
    if (list == null || list.isEmpty())
        return Collections.emptyList();
    Collections.sort(list, Collections.reverseOrder());
    long period = periodInHours >= 0 ? periodInHours * HOUR : HOUR;
    final long coldThreshold = list.get(0).lastUpdated.getTime() - period;
    Collection<ReviewItem> hot = Collections2.filter(list, new Predicate<ReviewItem>() {
        public boolean apply(ReviewItem input) {
            return input.lastUpdated.getTime() >= coldThreshold; //check that the review is not too old
        }
    });
    Collection<ReviewItem> unhandled = Collections2.filter(hot, new NeedsBuild());
    Collection<String> res = Collections2.transform(unhandled, new Function<ReviewItem, String>() {
        public String apply(ReviewItem input) {
            return reviewNumberToUrl(Long.toString(input.id));
        }
    });
    return res;
}

From source file:com.facebook.android.friendsmash.ScoreboardFragment.java

private void fetchScoreboardEntries() {
    // Fetch the scores ...
    AsyncTask.execute(new Runnable() {
        public void run() {
            try {
                // Instantiate the scoreboardEntriesList
                ArrayList<ScoreboardEntry> scoreboardEntriesList = new ArrayList<ScoreboardEntry>();

                // Get the attributes used for the HTTP GET
                String currentUserFBID = application.getCurrentFBUser().getId();
                String currentUserAccessToken = Session.getActiveSession().getAccessToken();

                // Execute the HTTP Get to our server for the scores of the user's friends
                HttpClient client = new DefaultHttpClient();
                String getURL = "http://www.friendsmash.com/scores?fbid=" + currentUserFBID + "&access_token="
                        + currentUserAccessToken;
                HttpGet get = new HttpGet(getURL);
                HttpResponse responseGet = client.execute(get);

                // Parse the response
                HttpEntity responseEntity = responseGet.getEntity();
                String response = EntityUtils.toString(responseEntity);
                if (!response.equals(null)) {
                    JSONArray responseJSONArray = new JSONArray(response);

                    // Go through the response JSON Array to populate the scoreboard
                    if (responseJSONArray != null && responseJSONArray.length() > 0) {

                        // Loop through all users that have been retrieved
                        for (int i = 0; i < responseJSONArray.length(); i++) {
                            // Store the user details in the following attributes
                            String userID = null;
                            String userName = null;
                            int userScore = -1;

                            // Extract the user information
                            JSONObject currentUser = responseJSONArray.optJSONObject(i);
                            if (currentUser != null) {
                                userID = currentUser.optString("fbid");
                                userName = currentUser.optString("first_name");
                                String fetchedScoreAsString = currentUser.optString("highscore");
                                if (fetchedScoreAsString != null) {
                                    userScore = Integer.parseInt(fetchedScoreAsString);
                                }//from w  w  w.ja  va 2s  .  c om
                                if (userID != null && userName != null && userScore >= 0) {
                                    // All attributes have been successfully fetched, so create a new
                                    // ScoreboardEntry and add it to the List
                                    ScoreboardEntry currentUserScoreboardEntry = new ScoreboardEntry(userID,
                                            userName, userScore);
                                    scoreboardEntriesList.add(currentUserScoreboardEntry);
                                }
                            }
                        }
                    }
                }

                // Now that all scores should have been fetched and added to the scoreboardEntriesList, sort it,
                // set it within scoreboardFragment and then callback to scoreboardFragment to populate the scoreboard
                Comparator<ScoreboardEntry> comparator = Collections.reverseOrder();
                Collections.sort(scoreboardEntriesList, comparator);
                application.setScoreboardEntriesList(scoreboardEntriesList);

                // Populate the scoreboard on the UI thread
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        populateScoreboard();
                    }
                });
            } catch (Exception e) {
                Log.e(FriendSmashApplication.TAG, e.toString());
                closeAndShowError(getResources().getString(R.string.network_error));
            }
        }
    });
}

From source file:uk.co.flax.biosolr.builders.ParentNodeFacetTreeBuilder.java

/**
 * Recursively build an accumulated facet entry tree.
 * @param level current level in the tree (used for debugging/logging).
 * @param fieldValue the current node value.
 * @param hierarchyMap the map of nodes (either in the original facet set,
 * or parents of those entries)./*from w  ww .ja va2  s .c om*/
 * @param facetCounts the facet counts, keyed by node ID.
 * @return a {@link TreeFacetField} containing details for the current node and all
 * sub-nodes down to the lowest leaf which has a facet count.
 */
private TreeFacetField buildAccumulatedEntryTree(int level, String fieldValue,
        Map<String, Set<String>> hierarchyMap, Map<String, Integer> facetCounts) {
    // Build the child hierarchy for this entry.
    // We use a reverse-ordered SortedSet so entries are returned in descending
    // order by their total count.
    SortedSet<TreeFacetField> childHierarchy = new TreeSet<>(Collections.reverseOrder());

    // childTotal is the total number of facet hits below this node
    long childTotal = 0;
    if (hierarchyMap.containsKey(fieldValue)) {
        // Loop through all the direct child URIs, looking for those which are in the annotation map
        for (String childId : hierarchyMap.get(fieldValue)) {
            if (!childId.equals(fieldValue)) {
                // Found a child of this node - recurse to build its facet tree
                LOGGER.trace("[{}] Building child tree for {}, with {} children", level, childId,
                        (hierarchyMap.containsKey(childId) ? hierarchyMap.get(childId).size() : 0));
                TreeFacetField childTree = buildAccumulatedEntryTree(level + 1, childId, hierarchyMap,
                        facetCounts);

                // Only add to the total count if this node isn't already in the child hierarchy
                if (childHierarchy.add(childTree)) {
                    childTotal += childTree.getTotal();
                }
                LOGGER.trace("[{}] child tree total: {} - child Total {}, child count {}", level,
                        childTree.getTotal(), childTotal, childHierarchy.size());
            } else {
                LOGGER.trace("[{}] found self-referring ID {}->{}", level, fieldValue, childId);
            }
        }
    }

    // Build the accumulated facet entry
    LOGGER.trace("[{}] Building facet tree for {}", level, fieldValue);
    return new TreeFacetField(getLabel(fieldValue), fieldValue, getFacetCount(fieldValue, facetCounts),
            childTotal, childHierarchy);
}

From source file:com.daycle.daycleapp.custom.swipelistview.itemmanipulation.swipedismiss.SwipeDismissTouchListener.java

/**
 * Notifies the {@link OnDismissCallback} of dismissed items.
 *
 * @param dismissedPositions the positions that have been dismissed.
 *//*ww w. ja  v  a 2  s. co m*/
protected void notifyCallback(@NonNull final List<Integer> dismissedPositions) {
    if (!dismissedPositions.isEmpty()) {
        Collections.sort(dismissedPositions, Collections.reverseOrder());

        int[] dismissPositions = new int[dismissedPositions.size()];
        int i = 0;
        for (Integer dismissedPosition : dismissedPositions) {
            dismissPositions[i] = dismissedPosition;
            i++;
        }

        L.d("getFlingToRight: " + getFlingToRight());

        //    
        mCallback.onDismiss(getListViewWrapper().getListView(), dismissPositions, getFlingToRight());
    }
}

From source file:org.tinymediamanager.scraper.entities.MediaArtwork.java

/**
 * Get all available image sizes for this artwork
 * //from   w ww .j  av a  2  s .c om
 * @return a list of all available image sizes
 */
public List<ImageSizeAndUrl> getImageSizes() {
    List<ImageSizeAndUrl> descImageSizes = new ArrayList<>(imageSizes);

    // sort descending
    Collections.sort(descImageSizes, Collections.reverseOrder());

    return descImageSizes;
}

From source file:com.telenav.expandablepager.SlidingContainer.java

/**
 * Stops sliding at the specified values.
 * @param stopValues list of stop values
 *//*w w w  .j av  a2 s  .co  m*/
public void setStopValues(Float... stopValues) {
    SortedSet<Float> s = new TreeSet<>(Collections.reverseOrder());
    s.addAll(Arrays.asList(stopValues));
    this.stopValues.clear();
    this.stopValues.addAll(s);
    this.stopValues.add(0f);
    stopValueIndex = 0;
}