public void testImmutableSortedCopy() { ImmutableList<Integer> unsortedInts = ImmutableList.of(5, 3, 0, 9, 3); ImmutableList<Integer> sortedInts = numberOrdering.immutableSortedCopy(unsortedInts); assertEquals(Arrays.asList(0, 3, 3, 5, 9), sortedInts); assertEquals( Collections.<Integer>emptyList(), numberOrdering.immutableSortedCopy(Collections.<Integer>emptyList())); List<Integer> listWithNull = Arrays.asList(5, 3, null, 9); try { Ordering.natural().nullsFirst().immutableSortedCopy(listWithNull); fail(); } catch (NullPointerException expected) { } }
@GET("/backend/config/alerts") String getAlertList() throws JsonProcessingException { List<AlertConfigDto> alertConfigDtos = Lists.newArrayList(); List<AlertConfig> alertConfigs = configRepository.getAlertConfigs(); alertConfigs = orderingByName.immutableSortedCopy(alertConfigs); for (AlertConfig alertConfig : alertConfigs) { alertConfigDtos.add(AlertConfigDto.fromConfig(alertConfig)); } return mapper.writeValueAsString(alertConfigDtos); }
void testSortedCopy() { List<T> shuffledList = Lists.newArrayList(strictlyOrderedList); shuffledList = shuffledCopy(shuffledList, new Random(5)); assertEquals(strictlyOrderedList, ordering.sortedCopy(shuffledList)); if (!strictlyOrderedList.contains(null)) { assertEquals(strictlyOrderedList, ordering.immutableSortedCopy(shuffledList)); } }
@Override public Optional<ImmutableSet<PreemptionVictim>> filterPreemptionVictims( ITaskConfig pendingTask, Iterable<PreemptionVictim> possibleVictims, AttributeAggregate jobState, Optional<HostOffer> offer, StoreProvider storeProvider) { // This enforces the precondition that all of the resources are from the same host. We need to // get the host for the schedulingFilter. Set<String> hosts = ImmutableSet.<String>builder() .addAll(Iterables.transform(possibleVictims, VICTIM_TO_HOST)) .addAll(Iterables.transform(offer.asSet(), OFFER_TO_HOST)) .build(); ResourceSlot slackResources = sum(Iterables.transform(offer.asSet(), OFFER_TO_RESOURCE_SLOT)); FluentIterable<PreemptionVictim> preemptableTasks = FluentIterable.from(possibleVictims).filter(preemptionFilter(pendingTask)); if (preemptableTasks.isEmpty()) { return Optional.absent(); } Set<PreemptionVictim> toPreemptTasks = Sets.newHashSet(); Iterable<PreemptionVictim> sortedVictims = resourceOrder.immutableSortedCopy(preemptableTasks); Optional<IHostAttributes> attributes = storeProvider.getAttributeStore().getHostAttributes(Iterables.getOnlyElement(hosts)); if (!attributes.isPresent()) { metrics.recordMissingAttributes(); return Optional.absent(); } for (PreemptionVictim victim : sortedVictims) { toPreemptTasks.add(victim); ResourceSlot totalResource = sum(Iterables.transform(toPreemptTasks, victimToResources)).add(slackResources); Set<Veto> vetoes = schedulingFilter.filter( new UnusedResource(totalResource, attributes.get()), new ResourceRequest(pendingTask, jobState)); if (vetoes.isEmpty()) { return Optional.of(ImmutableSet.copyOf(toPreemptTasks)); } } return Optional.absent(); }
public void testAllEqual() { Ordering<Object> comparator = Ordering.allEqual(); assertSame(comparator, comparator.reverse()); assertEquals(comparator.compare(null, null), 0); assertEquals(comparator.compare(new Object(), new Object()), 0); assertEquals(comparator.compare("apples", "oranges"), 0); assertSame(comparator, reserialize(comparator)); assertEquals("Ordering.allEqual()", comparator.toString()); List<String> strings = ImmutableList.of("b", "a", "d", "c"); assertEquals(strings, comparator.sortedCopy(strings)); assertEquals(strings, comparator.immutableSortedCopy(strings)); }
public HashLine(char[] buffer, PathFragment defaultPath) { CharSequence bufString = CharBuffer.wrap(buffer); Matcher m = pattern.matcher(bufString); List<SingleHashLine> unorderedTable = new ArrayList<>(); Map<String, PathFragment> pathCache = new HashMap<>(); while (m.find()) { String pathString = m.group(2); PathFragment pathFragment = pathCache.get(pathString); if (pathFragment == null) { pathFragment = defaultPath.getRelative(pathString); pathCache.put(pathString, pathFragment); } unorderedTable.add( new SingleHashLine( m.start(0) + 1, // offset (+1 to skip \n in pattern) Integer.parseInt(m.group(1)), // line number pathFragment)); // filename is an absolute path } this.table = hashOrdering.immutableSortedCopy(unorderedTable); this.bufferLength = buffer.length; this.defaultPath = Preconditions.checkNotNull(defaultPath); }
/** * Generate a similarity matrix from a given set of submissions. * * @param inputSubmissions Submissions to generate from * @param results Results to build from. Must contain results for every possible unordered pair of * input submissions * @return Similarity Matrix built from given results * @throws InternalAlgorithmError Thrown on missing results, or results containing a submission * not in the input */ public static SimilarityMatrix generateMatrix( Set<Submission> inputSubmissions, Set<AlgorithmResults> results) throws InternalAlgorithmError { checkNotNull(inputSubmissions); checkNotNull(results); checkArgument( !inputSubmissions.isEmpty(), "Must provide at least 1 submission to build matrix from"); checkArgument( !results.isEmpty(), "Must provide at least 1 AlgorithmResults to build matrix from!"); // Generate the matrix we'll use AlgorithmResults[][] matrix = new AlgorithmResults[inputSubmissions.size()][inputSubmissions.size()]; // Ordering sortBy = Ordering.natural(); Ordering<Submission> sortBy = Ordering.from( new Comparator<Submission>() { public int compare(Submission a, Submission b) { return ((Double) b.getTotalCopyScore()).compareTo(a.getTotalCopyScore()); } }); // Order the submissions List<Submission> orderedSubmissions = sortBy.immutableSortedCopy(inputSubmissions); // Generate the matrix // Start with the diagonal, filling with 100% similarity for (int i = 0; i < orderedSubmissions.size(); i++) { Submission s = orderedSubmissions.get(i); matrix[i][i] = new AlgorithmResults(Pair.of(s, s), Real.ONE, Real.ONE); } // Now go through all the results, and build appropriate two MatrixEntry objects for each for (AlgorithmResults result : results) { int aIndex = orderedSubmissions.indexOf(result.a); int bIndex = orderedSubmissions.indexOf(result.b); if (aIndex == -1) { if (!result.a.testFlag("invalid")) { throw new InternalAlgorithmError( "Processed Algorithm Result with submission not in given input submissions with name \"" + result.a.getName() + "\""); } } else if (bIndex == -1) { if (!result.b.testFlag("invalid")) { throw new InternalAlgorithmError( "Processed Algorithm Result with submission not in given input submissions with name \"" + result.b.getName() + "\""); } } else { matrix[aIndex][bIndex] = result.inverse(); matrix[bIndex][aIndex] = result; } } // Verification pass: Go through and ensure that the entire array was populated for (int x = 0; x < orderedSubmissions.size(); x++) { for (int y = 0; y < orderedSubmissions.size(); y++) { if (matrix[x][y] == null) { throw new InternalAlgorithmError( "Missing Algorithm Results for comparison of submissions \"" + orderedSubmissions.get(x).getName() + "\" and \"" + orderedSubmissions.get(y).getName() + "\""); } } } return new SimilarityMatrix(matrix, orderedSubmissions, orderedSubmissions, results); }
// Used in bulk get API (getAccountPayments) private Payment toPayment( final PaymentModelDao curPaymentModelDao, final Iterable<PaymentTransactionModelDao> curTransactionsModelDao, @Nullable final Iterable<PaymentTransactionInfoPlugin> pluginTransactions, final InternalTenantContext internalTenantContext) { final Ordering<PaymentTransaction> perPaymentTransactionOrdering = Ordering.<PaymentTransaction>from( new Comparator<PaymentTransaction>() { @Override public int compare(final PaymentTransaction o1, final PaymentTransaction o2) { return o1.getEffectiveDate().compareTo(o2.getEffectiveDate()); } }); // Need to filter for optimized codepaths looking up by account_record_id final Iterable<PaymentTransactionModelDao> filteredTransactions = Iterables.filter( curTransactionsModelDao, new Predicate<PaymentTransactionModelDao>() { @Override public boolean apply(final PaymentTransactionModelDao curPaymentTransactionModelDao) { return curPaymentTransactionModelDao .getPaymentId() .equals(curPaymentModelDao.getId()); } }); PaymentModelDao newPaymentModelDao = curPaymentModelDao; final Collection<PaymentTransaction> transactions = new LinkedList<PaymentTransaction>(); for (final PaymentTransactionModelDao curPaymentTransactionModelDao : filteredTransactions) { PaymentTransactionModelDao newPaymentTransactionModelDao = curPaymentTransactionModelDao; final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin = findPaymentTransactionInfoPlugin(newPaymentTransactionModelDao, pluginTransactions); if (paymentTransactionInfoPlugin != null) { // Make sure to invoke the Janitor task in case the plugin fixes its state on the fly // See https://github.com/killbill/killbill/issues/341 final boolean hasChanged = incompletePaymentTransactionTask.updatePaymentAndTransactionIfNeededWithAccountLock( newPaymentModelDao, newPaymentTransactionModelDao, paymentTransactionInfoPlugin, internalTenantContext); if (hasChanged) { newPaymentModelDao = paymentDao.getPayment(newPaymentModelDao.getId(), internalTenantContext); newPaymentTransactionModelDao = paymentDao.getPaymentTransaction( newPaymentTransactionModelDao.getId(), internalTenantContext); } } final PaymentTransaction transaction = new DefaultPaymentTransaction( newPaymentTransactionModelDao.getId(), newPaymentTransactionModelDao.getAttemptId(), newPaymentTransactionModelDao.getTransactionExternalKey(), newPaymentTransactionModelDao.getCreatedDate(), newPaymentTransactionModelDao.getUpdatedDate(), newPaymentTransactionModelDao.getPaymentId(), newPaymentTransactionModelDao.getTransactionType(), newPaymentTransactionModelDao.getEffectiveDate(), newPaymentTransactionModelDao.getTransactionStatus(), newPaymentTransactionModelDao.getAmount(), newPaymentTransactionModelDao.getCurrency(), newPaymentTransactionModelDao.getProcessedAmount(), newPaymentTransactionModelDao.getProcessedCurrency(), newPaymentTransactionModelDao.getGatewayErrorCode(), newPaymentTransactionModelDao.getGatewayErrorMsg(), paymentTransactionInfoPlugin); transactions.add(transaction); } final List<PaymentTransaction> sortedTransactions = perPaymentTransactionOrdering.immutableSortedCopy(transactions); return new DefaultPayment( curPaymentModelDao.getId(), curPaymentModelDao.getCreatedDate(), curPaymentModelDao.getUpdatedDate(), curPaymentModelDao.getAccountId(), curPaymentModelDao.getPaymentMethodId(), curPaymentModelDao.getPaymentNumber(), curPaymentModelDao.getExternalKey(), sortedTransactions); }
final List<MeasureFilterRow> sort(List<MeasureFilterRow> rows, boolean ascending) { Ordering<MeasureFilterRow> ordering = sortFieldOrdering(ascending).onResultOf(sortFieldFunction()); return ordering.immutableSortedCopy(rows); }