List of usage examples for com.google.common.collect Ordering Ordering
protected Ordering()
From source file:org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.CollectionContentsSortableDataProvider.java
private static Ordering<ObjectAdapter> orderingBy(final ObjectAssociation sortProperty, final boolean ascending) { final Ordering<ObjectAdapter> ordering = new Ordering<ObjectAdapter>() { @Override/*from ww w . j a v a 2 s.co m*/ public int compare(final ObjectAdapter p, final ObjectAdapter q) { final ObjectAdapter pSort = sortProperty.get(p, InteractionInitiatedBy.FRAMEWORK); final ObjectAdapter qSort = sortProperty.get(q, InteractionInitiatedBy.FRAMEWORK); Ordering<ObjectAdapter> naturalOrdering; if (ascending) { naturalOrdering = ORDERING_BY_NATURAL.nullsFirst(); } else { naturalOrdering = ORDERING_BY_NATURAL.reverse().nullsLast(); } return naturalOrdering.compare(pSort, qSort); } }; return ordering; }
From source file:com.palantir.util.Pair.java
/** * Returns a <code>Comparator</code> for the * right-hand side object of the <code>Pair</code>. *//*from w ww.j a v a2 s . c om*/ public static <T, W> Ordering<Pair<T, W>> compareRhSide(final Comparator<? super W> comp) { return new Ordering<Pair<T, W>>() { @Override public int compare(Pair<T, W> o1, Pair<T, W> o2) { return comp.compare(o1.rhSide, o2.rhSide); } }; }
From source file:com.metamx.druid.merger.coordinator.TaskQueue.java
/** * Starts this task queue. Loads tasks from our task storage facility and allows {@link #add(Task)} to accept * new tasks. This should not be called on an already-started queue. *///from ww w . ja v a 2 s .c o m @LifecycleStart public void start() { giant.lock(); try { Preconditions.checkState(!active, "queue was already started!"); Preconditions.checkState(queue.isEmpty(), "queue must be empty!"); Preconditions.checkState(running.isEmpty(), "running list must be empty!"); // XXX - We might want a TaskStorage API that does this, but including the Pair type in the interface seems clumsy. final List<Pair<Task, String>> runningTasks = Lists.transform(taskStorage.getRunningTasks(), new Function<Task, Pair<Task, String>>() { @Override public Pair<Task, String> apply(Task task) { return Pair.of(task, taskStorage.getVersion(task.getId()).orNull()); } }); // Sort by version, with nulls last final Ordering<Pair<Task, String>> byVersionOrdering = new Ordering<Pair<Task, String>>() { final private Ordering<String> baseOrdering = Ordering.natural().nullsLast(); @Override public int compare(Pair<Task, String> left, Pair<Task, String> right) { return baseOrdering.compare(left.rhs, right.rhs); } }; for (final Pair<Task, String> taskAndVersion : byVersionOrdering.sortedCopy(runningTasks)) { final Task task = taskAndVersion.lhs; final String preferredVersion = taskAndVersion.rhs; queue.add(task); if (preferredVersion != null) { final Optional<String> version = tryLock(task, Optional.of(preferredVersion)); log.info("Bootstrapped task[%s] with preferred version[%s]: %s", task.getId(), preferredVersion, version.isPresent() ? String.format("locked with version[%s]", version.get()) : "not lockable"); } else { log.info("Bootstrapped task[%s] with no preferred version", task.getId()); } } log.info("Bootstrapped %,d tasks. Ready to go!", runningTasks.size()); active = true; workMayBeAvailable.signalAll(); } finally { giant.unlock(); } }
From source file:com.metamx.druid.indexing.coordinator.TaskQueue.java
/** * Bootstraps this task queue and associated task lockbox. Clears the lockbox before running. Should be called * while the queue is stopped. It is not a good idea to start the queue if this method fails. *//*from ww w . jav a 2 s . co m*/ public void bootstrap() { // NOTE: Bootstraps can resurrect bogus stuff caused by leader races or whatevs. // We may want to periodically fixup the database to refer to what we think is happening, to prevent // this from occurring and also so that bogus stuff is detected by clients in a timely manner. giant.lock(); try { Preconditions.checkState(!active, "queue must be stopped"); log.info("Bootstrapping queue (and associated lockbox)"); queue.clear(); taskLockbox.clear(); // Get all running tasks and their locks final Multimap<TaskLock, Task> tasksByLock = ArrayListMultimap.create(); for (final Task task : taskStorage.getRunningTasks()) { try { final List<TaskLock> taskLocks = taskStorage.getLocks(task.getId()); queue.add(task); for (final TaskLock taskLock : taskLocks) { tasksByLock.put(taskLock, task); } } catch (Exception e) { log.makeAlert("Failed to bootstrap task").addData("task", task.getId()).emit(); throw Throwables.propagate(e); } } // Sort locks by version final Ordering<Map.Entry<TaskLock, Task>> byVersionOrdering = new Ordering<Map.Entry<TaskLock, Task>>() { @Override public int compare(Map.Entry<TaskLock, Task> left, Map.Entry<TaskLock, Task> right) { return left.getKey().getVersion().compareTo(right.getKey().getVersion()); } }; // Acquire as many locks as possible, in version order for (final Map.Entry<TaskLock, Task> taskAndLock : byVersionOrdering .sortedCopy(tasksByLock.entries())) { final Task task = taskAndLock.getValue(); final TaskLock savedTaskLock = taskAndLock.getKey(); final Optional<TaskLock> acquiredTaskLock = taskLockbox.tryLock(task, savedTaskLock.getInterval(), Optional.of(savedTaskLock.getVersion())); if (acquiredTaskLock.isPresent() && savedTaskLock.getVersion().equals(acquiredTaskLock.get().getVersion())) { log.info("Reacquired lock on interval[%s] version[%s] for task: %s", savedTaskLock.getInterval(), savedTaskLock.getVersion(), task.getId()); } else if (acquiredTaskLock.isPresent()) { log.info( "Could not reacquire lock on interval[%s] version[%s] (got version[%s] instead) for task: %s", savedTaskLock.getInterval(), savedTaskLock.getVersion(), acquiredTaskLock.get().getVersion(), task.getId()); } else { log.info("Could not reacquire lock on interval[%s] version[%s] for task: %s", savedTaskLock.getInterval(), savedTaskLock.getVersion(), task.getId()); } } log.info("Bootstrapped %,d tasks with %,d locks. Ready to go!", queue.size(), tasksByLock.keySet().size()); } finally { giant.unlock(); } }
From source file:org.eclipse.buildship.ui.view.task.TaskNodeViewerSorter.java
private static Ordering<TaskNode> createByTypeOrdering() { return new Ordering<TaskNode>() { @Override// w ww . j a va 2 s . co m public int compare(TaskNode left, TaskNode right) { int leftOrdinal = toOrdinal(left.getType()); int rightOrdinal = toOrdinal(right.getType()); return (leftOrdinal < rightOrdinal ? -1 : (leftOrdinal == rightOrdinal ? 0 : 1)); } private int toOrdinal(TaskNodeType type) { // project tasks to be shown first return type == TaskNodeType.PROJECT_TASK_NODE ? 1 : 2; } }; }
From source file:io.ssc.trackthetrackers.analysis.stats.LogLikelihood.java
/** * Compares two sets of counts to see which items are interestingly over-represented in the first * set.//from w w w . j ava2s . c o m * @param a The first counts. * @param b The reference counts. * @param maxReturn The maximum number of items to return. Use maxReturn >= a.elementSet.size() to return all * scores above the threshold. * @param threshold The minimum score for items to be returned. Use 0 to return all items more common * in a than b. Use -Double.MAX_VALUE (not Double.MIN_VALUE !) to not use a threshold. * @return A list of scored items with their scores. */ public static <T> List<ScoredItem<T>> compareFrequencies(Multiset<T> a, Multiset<T> b, int maxReturn, double threshold) { int totalA = a.size(); int totalB = b.size(); Ordering<ScoredItem<T>> byScoreAscending = new Ordering<ScoredItem<T>>() { @Override public int compare(ScoredItem<T> tScoredItem, ScoredItem<T> tScoredItem1) { return Double.compare(tScoredItem.score, tScoredItem1.score); } }; Queue<ScoredItem<T>> best = new PriorityQueue<ScoredItem<T>>(maxReturn + 1, byScoreAscending); for (T t : a.elementSet()) { compareAndAdd(a, b, maxReturn, threshold, totalA, totalB, best, t); } // if threshold >= 0 we only iterate through a because anything not there can't be as or more common than in b. if (threshold < 0) { for (T t : b.elementSet()) { // only items missing from a need be scored if (a.count(t) == 0) { compareAndAdd(a, b, maxReturn, threshold, totalA, totalB, best, t); } } } List<ScoredItem<T>> r = new ArrayList<ScoredItem<T>>(best); Collections.sort(r, byScoreAscending.reverse()); return r; }
From source file:org.apache.mahout.math.stats.LogLikelihood.java
/** * Compares two sets of counts to see which items are interestingly over-represented in the first * set./*from w w w . j a v a 2 s. co m*/ * @param a The first counts. * @param b The reference counts. * @param maxReturn The maximum number of items to return. Use maxReturn >= a.elementSet.size() to return all * scores above the threshold. * @param threshold The minimum score for items to be returned. Use 0 to return all items more common * in a than b. Use -Double.MAX_VALUE (not Double.MIN_VALUE !) to not use a threshold. * @return A list of scored items with their scores. */ public static <T> List<ScoredItem<T>> compareFrequencies(Multiset<T> a, Multiset<T> b, int maxReturn, double threshold) { int totalA = a.size(); int totalB = b.size(); Ordering<ScoredItem<T>> byScoreAscending = new Ordering<ScoredItem<T>>() { @Override public int compare(ScoredItem<T> tScoredItem, ScoredItem<T> tScoredItem1) { return Double.compare(tScoredItem.score, tScoredItem1.score); } }; Queue<ScoredItem<T>> best = new PriorityQueue<ScoredItem<T>>(maxReturn + 1, byScoreAscending); for (T t : a.elementSet()) { compareAndAdd(a, b, maxReturn, threshold, totalA, totalB, best, t); } // if threshold >= 0 we only iterate through a because anything not there can't be as or more common than in b. if (threshold < 0) { for (T t : b.elementSet()) { // only items missing from a need be scored if (a.count(t) == 0) { compareAndAdd(a, b, maxReturn, threshold, totalA, totalB, best, t); } } } List<ScoredItem<T>> r = Lists.newArrayList(best); Collections.sort(r, byScoreAscending.reverse()); return r; }
From source file:org.syncany.plugins.transfer.TransferPluginOptions.java
private static List<Field> getOrderedFields(Class<? extends TransferSettings> transferSettingsClass) { Ordering<Field> byOrderAnnotation = new Ordering<Field>() { @Override/*from w w w. j a va 2 s . c o m*/ public int compare(Field leftField, Field rightField) { int leftOrderValue = (leftField.getAnnotation(Setup.class) != null) ? leftField.getAnnotation(Setup.class).order() : -1; int rightOrderValue = (rightField.getAnnotation(Setup.class) != null) ? rightField.getAnnotation(Setup.class).order() : -1; return Ints.compare(leftOrderValue, rightOrderValue); } }; List<Field> fields = Lists .newArrayList(ReflectionUtil.getAllFieldsWithAnnotation(transferSettingsClass, Element.class)); return ImmutableList.copyOf(byOrderAnnotation.nullsLast().sortedCopy(fields)); }
From source file:org.dbpedia.spotlight.lucene.disambiguate.LucenePriorDisambiguator.java
@Override public List<DBpediaResourceOccurrence> bestK(SurfaceFormOccurrence sfOccurrence, int k) throws SearchException, ItemNotFoundException { List<DBpediaResourceOccurrence> resultOccs = new LinkedList<DBpediaResourceOccurrence>(); for (DBpediaResource resource : mSearcher.getCandidates(sfOccurrence.surfaceForm())) { DBpediaResourceOccurrence occ = new DBpediaResourceOccurrence(resource, sfOccurrence.surfaceForm(), sfOccurrence.context(), sfOccurrence.textOffset()); //1 / numUris); //this is not really similarity score. TODO set this or not? resultOccs.add(occ);//from w w w . ja v a2 s.c om } if (resultOccs.isEmpty()) throw new SearchException("Could not find surface form " + sfOccurrence.surfaceForm()); Ordering descOrder = new Ordering<DBpediaResourceOccurrence>() { public int compare(DBpediaResourceOccurrence left, DBpediaResourceOccurrence right) { return Doubles.compare(right.resource().support(), left.resource().support()); } }; return descOrder.sortedCopy(resultOccs).subList(0, Math.min(k, resultOccs.size())); }
From source file:org.apache.druid.indexing.overlord.TaskLockbox.java
/** * Wipe out our current in-memory state and resync it from our bundled {@link TaskStorage}. *//* w ww . ja v a 2 s . c om*/ public void syncFromStorage() { giant.lock(); try { // Load stuff from taskStorage first. If this fails, we don't want to lose all our locks. final Set<String> storedActiveTasks = Sets.newHashSet(); final List<Pair<Task, TaskLock>> storedLocks = Lists.newArrayList(); for (final Task task : taskStorage.getActiveTasks()) { storedActiveTasks.add(task.getId()); for (final TaskLock taskLock : taskStorage.getLocks(task.getId())) { storedLocks.add(Pair.of(task, taskLock)); } } // Sort locks by version, so we add them back in the order they were acquired. final Ordering<Pair<Task, TaskLock>> byVersionOrdering = new Ordering<Pair<Task, TaskLock>>() { @Override public int compare(Pair<Task, TaskLock> left, Pair<Task, TaskLock> right) { // The second compare shouldn't be necessary, but, whatever. return ComparisonChain.start().compare(left.rhs.getVersion(), right.rhs.getVersion()) .compare(left.lhs.getId(), right.lhs.getId()).result(); } }; running.clear(); activeTasks.clear(); activeTasks.addAll(storedActiveTasks); // Bookkeeping for a log message at the end int taskLockCount = 0; for (final Pair<Task, TaskLock> taskAndLock : byVersionOrdering.sortedCopy(storedLocks)) { final Task task = taskAndLock.lhs; final TaskLock savedTaskLock = taskAndLock.rhs; if (savedTaskLock.getInterval().toDurationMillis() <= 0) { // "Impossible", but you never know what crazy stuff can be restored from storage. log.warn("WTF?! Got lock[%s] with empty interval for task: %s", savedTaskLock, task.getId()); continue; } // Create a new taskLock if it doesn't have a proper priority, // so that every taskLock in memory has the priority. final TaskLock savedTaskLockWithPriority = savedTaskLock.getPriority() == null ? TaskLock.withPriority(savedTaskLock, task.getPriority()) : savedTaskLock; final TaskLockPosse taskLockPosse = createOrFindLockPosse(task, savedTaskLockWithPriority); if (taskLockPosse != null) { taskLockPosse.addTask(task); final TaskLock taskLock = taskLockPosse.getTaskLock(); if (savedTaskLockWithPriority.getVersion().equals(taskLock.getVersion())) { taskLockCount++; log.info("Reacquired lock[%s] for task: %s", taskLock, task.getId()); } else { taskLockCount++; log.info( "Could not reacquire lock on interval[%s] version[%s] (got version[%s] instead) for task: %s", savedTaskLockWithPriority.getInterval(), savedTaskLockWithPriority.getVersion(), taskLock.getVersion(), task.getId()); } } else { throw new ISE("Could not reacquire lock on interval[%s] version[%s] for task: %s", savedTaskLockWithPriority.getInterval(), savedTaskLockWithPriority.getVersion(), task.getId()); } } log.info("Synced %,d locks for %,d activeTasks from storage (%,d locks ignored).", taskLockCount, activeTasks.size(), storedLocks.size() - taskLockCount); } finally { giant.unlock(); } }