List of usage examples for java.util Collections reverseOrder
@SuppressWarnings("unchecked") public static <T> Comparator<T> reverseOrder()
From source file:org.jenkinsci.plugins.jenkinsreviewbot.ReviewboardOps.java
public Collection<Review.Slim> getPendingReviews(final ReviewboardConnection con, long periodInHours, boolean restrictByUser, int repoid) throws IOException, JAXBException, ParseException { ensureAuthentication(con, http);/*from w ww .ja v a 2 s. c o m*/ ReviewsResponse response = getResponse(http, con.getPendingReviewsUrl(restrictByUser, repoid), 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 } }); Function<ReviewItem, Review> enrich = new Function<ReviewItem, Review>() { public Review apply(@Nullable ReviewItem input) { Response d = getResponse(http, con.getDiffsUrl(input.id), Response.class); Date lastUploadTime = d.count < 1 ? null : d.diffs.array.get(d.count - 1).timestamp; String url = con.reviewNumberToUrl(Long.toString(input.id)); return new Review(url, lastUploadTime, input); } }; Collection<Review> hotRich = Collections2.transform(hot, enrich); Predicate<Review> needsBuild = new Predicate<Review>() { public boolean apply(Review input) { if (input.getLastUpdate() == null) return false; //no diffs found Response c = getResponse(http, con.getCommentsUrl(input.getInput().id), Response.class); //no comments from this user after last diff upload for (Item r : c.reviews.array) { if (con.getReviewboardUsername().equals(r.links.user.title) && r.timestamp.after(input.getLastUpdate())) { return false; } } return true; } }; Collection<Review> unhandled = Collections2.filter(hotRich, needsBuild); Function<Review, Review.Slim> trim = new Function<Review, Review.Slim>() { public Review.Slim apply(@Nullable Review input) { return input.trim(); } }; return Collections2.transform(unhandled, trim); }
From source file:com.almende.demo.conferenceApp.ConferenceAgent.java
public List<Info> getList(final boolean filterIgnored) { List<Info> result = new ArrayList<Info>(); if (getState() != null && getState().containsKey(CONTACTKEY.getKey())) { HashMap<String, Info> contacts = getState().get(CONTACTKEY); for (Info info : contacts.values()) { if (info.isKnown() && !info.isIgnored()) { result.add(info);//from www . ja va2s . com } } } Collections.sort(result, Collections.reverseOrder()); return result; }
From source file:uk.co.flax.biosolr.builders.ChildNodeFacetTreeBuilder.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)./* w w w.j a v a 2 s . co m*/ * @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 (hierarchyMap.containsKey(childId) && !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.get(childId).size()); 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("[{}] no node entry for {}->{}", 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:org.tinymediamanager.scraper.entities.MediaArtwork.java
/** * Get the biggest artwork if different sizes are available or null * /* ww w . j a v a 2s . c o m*/ * @return the biggest artwork or null */ public ImageSizeAndUrl getBiggestArtwork() { if (imageSizes.size() > 0) { List<ImageSizeAndUrl> descImageSizes = new ArrayList<>(imageSizes); // sort descending Collections.sort(descImageSizes, Collections.reverseOrder()); ImageSizeAndUrl biggestImage = descImageSizes.get(0); if (biggestImage != null) { return biggestImage; } } return null; }
From source file:org.broadleafcommerce.core.offer.service.processor.FulfillmentGroupOfferProcessorImpl.java
@Override @SuppressWarnings("unchecked") public boolean applyAllFulfillmentGroupOffers(List<PromotableCandidateFulfillmentGroupOffer> qualifiedFGOffers, PromotableOrder order) {/*from w w w . j a va 2s . co m*/ Map<FulfillmentGroupOfferPotential, List<PromotableCandidateFulfillmentGroupOffer>> offerMap = new HashMap<FulfillmentGroupOfferPotential, List<PromotableCandidateFulfillmentGroupOffer>>(); for (PromotableCandidateFulfillmentGroupOffer candidate : qualifiedFGOffers) { FulfillmentGroupOfferPotential potential = new FulfillmentGroupOfferPotential(); potential.setOffer(candidate.getOffer()); if (offerMap.get(potential) == null) { offerMap.put(potential, new ArrayList<PromotableCandidateFulfillmentGroupOffer>()); } offerMap.get(potential).add(candidate); } List<FulfillmentGroupOfferPotential> potentials = new ArrayList<FulfillmentGroupOfferPotential>(); for (FulfillmentGroupOfferPotential potential : offerMap.keySet()) { List<PromotableCandidateFulfillmentGroupOffer> fgOffers = offerMap.get(potential); Collections.sort(fgOffers, new ReverseComparator(new BeanComparator("discountedAmount", new NullComparator()))); Collections.sort(fgOffers, new BeanComparator("priority", new NullComparator())); if (potential.getOffer().isLimitedUsePerOrder() && fgOffers.size() > potential.getOffer().getMaxUsesPerOrder()) { for (int j = potential.getOffer().getMaxUsesPerOrder(); j < fgOffers.size(); j++) { fgOffers.remove(j); } } for (PromotableCandidateFulfillmentGroupOffer candidate : fgOffers) { if (potential.getTotalSavings().getAmount().equals(BankersRounding.zeroAmount())) { BroadleafCurrency currency = order.getOrderCurrency(); if (currency != null) { potential.setTotalSavings(new Money(BigDecimal.ZERO, currency.getCurrencyCode())); } else { potential.setTotalSavings(new Money(BigDecimal.ZERO)); } } Money priceBeforeAdjustments = candidate.getFulfillmentGroup().calculatePriceWithoutAdjustments(); Money discountedPrice = candidate.getDiscountedPrice(); potential.setTotalSavings( potential.getTotalSavings().add(priceBeforeAdjustments.subtract(discountedPrice))); potential.setPriority(candidate.getOffer().getPriority()); } potentials.add(potential); } // Sort fg potentials by priority and discount Collections.sort(potentials, new BeanComparator("totalSavings", Collections.reverseOrder())); Collections.sort(potentials, new BeanComparator("priority")); potentials = removeTrailingNotCombinableFulfillmentGroupOffers(potentials); boolean fgOfferApplied = false; for (FulfillmentGroupOfferPotential potential : potentials) { Offer offer = potential.getOffer(); boolean alreadyContainsTotalitarianOffer = order.isTotalitarianOfferApplied(); List<PromotableCandidateFulfillmentGroupOffer> candidates = offerMap.get(potential); for (PromotableCandidateFulfillmentGroupOffer candidate : candidates) { applyFulfillmentGroupOffer(candidate.getFulfillmentGroup(), candidate); fgOfferApplied = true; } for (PromotableFulfillmentGroup fg : order.getFulfillmentGroups()) { fg.chooseSaleOrRetailAdjustments(); } if ((offer.isTotalitarianOffer() != null && offer.isTotalitarianOffer()) || alreadyContainsTotalitarianOffer) { fgOfferApplied = compareAndAdjustFulfillmentGroupOffers(order, fgOfferApplied); if (fgOfferApplied) { break; } } else if (!offer.isCombinableWithOtherOffers()) { break; } } return fgOfferApplied; }
From source file:com.gsoc.ijosa.liquidgalaxycontroller.PW.collection.PhysicalWebCollection.java
/** * Return a list of PwPairs sorted by rank in descending order, including only the top-ranked * pair from each group./*from www. j av a2 s . c o m*/ * @return a sorted list of PwPairs. */ public List<PwPair> getGroupedPwPairsSortedByRank() { // Get all valid PwPairs. List<PwPair> allPwPairs = getPwPairs(); // Group pairs with the same groupId, keeping only the top-ranked PwPair. List<PwPair> groupedPwPairs = removeDuplicateGroupIds(allPwPairs, null); // Sort by descending rank. Collections.sort(groupedPwPairs, Collections.reverseOrder()); // Remove duplicate site URLs. return removeDuplicateSiteUrls(groupedPwPairs); }
From source file:com.liato.bankdroid.banking.banks.SEBKortBase.java
@Override public void updateTransactions(Account account, Urllib urlopen) throws LoginException, BankException { super.updateTransactions(account, urlopen); if (!urlopen.acceptsInvalidCertificates()) { //Should never happen, but we'll check it anyway. urlopen = login();//from w w w . ja va 2 s.c om } if (account.getType() != Account.CCARD) return; String response = null; Matcher matcher; try { response = urlopen.open(String .format("https://application.sebkort.com/nis/%s/getPendingTransactions.do", provider_part)); matcher = reTransactions.matcher(response); ArrayList<Transaction> transactions = new ArrayList<Transaction>(); while (matcher.find()) { /* * Capture groups: * GROUP EXAMPLE DATA * 1: Trans. date 10-18 * 2: Book. date 10-19 * 3: Specification ICA Kvantum * 4: Location Stockholm * 5: Currency currency code (e.g. EUR) for transactions in non-SEK * 6: Amount local currency amount (in $currency) for transactions in non-SEK * 7: Amount in sek 5791,18 * */ String[] monthday = matcher.group(1).trim().split("-"); transactions.add(new Transaction(Helpers.getTransactionDate(monthday[0], monthday[1]), Html.fromHtml(matcher.group(3)).toString().trim() + (matcher.group(4).trim().length() > 0 ? " (" + Html.fromHtml(matcher.group(4)).toString().trim() + ")" : ""), Helpers.parseBalance(matcher.group(7)).negate())); 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:ca.mcgill.cs.creco.logic.ScoredAttribute.java
private void setNumericStats(ArrayList<TypedValue> pValues) { SummaryStatistics ss = new SummaryStatistics(); double min = DEFAULT_MIN; double max = DEFAULT_MAX; ArrayList<Double> values = new ArrayList<Double>(pValues.size()); for (TypedValue tv : pValues) { if (tv.isNumeric()) { ss.addValue(tv.getNumeric()); if (tv.getNumeric() < min) { min = tv.getNumeric();//from ww w .ja va2 s .co m } if (tv.getNumeric() > max) { max = tv.getNumeric(); } values.add(tv.getNumeric()); } } //Set bounds if (Double.isNaN(min)) { LOG.error("Min value is NaN: " + aAttributeID + ", " + aAttributeName + ", " + aCategory.getId()); } if (Double.isNaN(max)) { LOG.error("Max value is NaN: " + aAttributeID + ", " + aAttributeName + ", " + aCategory.getId()); } aMin = new TypedValue(min); aMax = new TypedValue(max); double mean = ss.getGeometricMean(); double variance = ss.getStandardDeviation() * ss.getStandardDeviation(); //Calculate Entropy double entropy = 0; for (TypedValue tv : pValues) { if (tv.isNumeric()) { double prob = computeNormalProbability(tv, mean, variance); entropy = entropy - prob * (Math.log(prob)); } } aDefaultValue = new TypedValue(mean); if (!Double.isNaN(entropy)) { aEntropy = entropy; } else { aEntropy = 0; } //Get the correlation NumericCorrelator ac = new NumericCorrelator(aCategory); aCorrelation = ac.computeCorrelation(aAttributeID, CONSIDERATION_THRESHOLD); if (aIsPrice) { aDirection = Direction.LESS_IS_BETTER; } else { aDirection = ac.computeAttributeDirection(aAttributeID, CONSIDERATION_THRESHOLD); } //Calculate Ranking if (aDirection == Direction.LESS_IS_BETTER) { Collections.sort(values); } else { Collections.sort(values, Collections.reverseOrder()); } setRank(values); }
From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMultiplePanel.java
private void createToolbar() { ActionListener addAL = new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultTableModel model = (DefaultTableModel) formatSwitchTbl.getModel(); DataObjSwitchFormatter fmt = formatContainer.getSelectedFormatter(); DataObjDataFieldFormat fld = new DataObjDataFieldFormat(); fmt.add(fld);/* w ww.j a va2 s. com*/ model.addRow(new Object[] { fld.getValue(), fld, ellipsisButtonLabel }); setHasChanged(true); enableUIControls(); } }; ActionListener delAL = new ActionListener() { public void actionPerformed(ActionEvent e) { int formatColumn = formatSwitchTbl.getColumn(DISPLAY_FORMAT_COL).getModelIndex(); DefaultTableModel model = (DefaultTableModel) formatSwitchTbl.getModel(); DataObjSwitchFormatter fmt = formatContainer.getSelectedFormatter(); int[] rows = formatSwitchTbl.getSelectedRows(); // sort rows in reverse order otherwise removing the first rows // will mess up with the row numbers Integer[] intRows = new Integer[rows.length]; for (int i = 0; i < rows.length; ++i) { intRows[i] = new Integer(rows[i]); } Arrays.sort(intRows, Collections.reverseOrder()); for (int currentRow : intRows) { fmt.remove((DataObjDataFieldFormatIFace) model.getValueAt(currentRow, formatColumn)); model.removeRow(currentRow); } formatSwitchTbl.clearSelection(); setHasChanged(true); enableUIControls(); } }; controlPanel = new EditDeleteAddPanel(null, delAL, addAL); controlPanel.getAddBtn().setEnabled(true); }
From source file:com.netflix.metacat.connector.hive.HiveConnectorPartitionService.java
private List<Partition> getPartitions(final QualifiedName tableName, @Nullable final String filter, @Nullable final List<String> partitionIds, @Nullable final Sort sort, @Nullable final Pageable pageable) { final String databasename = tableName.getDatabaseName(); final String tablename = tableName.getTableName(); try {/* ww w .j av a2 s .c o m*/ final Table table = metacatHiveClient.getTableByName(databasename, tablename); List<Partition> partitionList = null; if (!Strings.isNullOrEmpty(filter)) { partitionList = metacatHiveClient.listPartitionsByFilter(databasename, tablename, filter); } else { if (partitionIds != null) { partitionList = metacatHiveClient.getPartitions(databasename, tablename, partitionIds); } if (partitionList == null || partitionList.isEmpty()) { partitionList = metacatHiveClient.getPartitions(databasename, tablename, null); } } final List<Partition> filteredPartitionList = Lists.newArrayList(); partitionList.forEach(partition -> { final String partitionName = getNameOfPartition(table, partition); if (partitionIds == null || partitionIds.contains(partitionName)) { filteredPartitionList.add(partition); } }); if (sort != null) { if (sort.getOrder() == SortOrder.DESC) { filteredPartitionList.sort(Collections.reverseOrder()); } else { Collections.sort(filteredPartitionList); } } return ConnectorUtils.paginate(filteredPartitionList, pageable); } catch (NoSuchObjectException exception) { throw new TableNotFoundException(tableName, exception); } catch (MetaException | InvalidObjectException e) { throw new InvalidMetaException("Invalid metadata for " + tableName, e); } catch (TException e) { throw new ConnectorException(String.format("Failed get partitions for hive table %s", tableName), e); } }