Example usage for com.google.common.collect Ordering sortedCopy

List of usage examples for com.google.common.collect Ordering sortedCopy

Introduction

In this page you can find the example usage for com.google.common.collect Ordering sortedCopy.

Prototype

public <E extends T> List<E> sortedCopy(Iterable<E> elements) 

Source Link

Document

Returns a mutable list containing elements sorted by this ordering; use this only when the resulting list may need further modification, or may contain null .

Usage

From source file:com.eucalyptus.tags.TagManager.java

public DescribeTagsResponseType describeTags(final DescribeTagsType request) throws Exception {
    final DescribeTagsResponseType reply = request.getReply();
    final Context context = Contexts.lookup();

    final Filter filter = Filters.generate(request.getFilterSet(), Tag.class);
    final Ordering<Tag> ordering = Ordering.natural().onResultOf(Tags.resourceId())
            .compound(Ordering.natural().onResultOf(Tags.key()))
            .compound(Ordering.natural().onResultOf(Tags.value()));
    Iterables//from  w w  w.  ja va  2  s .c o  m
            .addAll(reply.getTagSet(),
                    Iterables
                            .transform(
                                    ordering.sortedCopy(Tags.list(context.getUserFullName().asAccountFullName(),
                                            Predicates.and(filter.asPredicate(),
                                                    RestrictedTypes.<Tag>filterPrivileged()),
                                            filter.asCriterion(), filter.getAliases())),
                                    TypeMappers.lookup(Tag.class, TagInfo.class)));

    return reply;
}

From source file:io.redlink.sdk.impl.analysis.model.Enhancements.java

/**
 * Returns the best {@link EntityAnnotation}s (those with the highest confidence value) for each extracted {@link TextAnnotation}
 *
 * @return best annotations// w  w w  .ja v a  2s.  co  m
 */
public Multimap<TextAnnotation, EntityAnnotation> getBestAnnotations() {

    Ordering<EntityAnnotation> o = new Ordering<EntityAnnotation>() {
        @Override
        public int compare(EntityAnnotation left, EntityAnnotation right) {
            return Doubles.compare(left.confidence, right.confidence);
        }
    }.reverse();

    Multimap<TextAnnotation, EntityAnnotation> result = ArrayListMultimap.create();
    for (TextAnnotation ta : getTextAnnotations()) {
        List<EntityAnnotation> eas = o.sortedCopy(getEntityAnnotations(ta));
        if (!eas.isEmpty()) {
            Collection<EntityAnnotation> highest = new HashSet<>();
            Double confidence = eas.get(0).getConfidence();
            for (EntityAnnotation ea : eas) {
                if (ea.confidence < confidence) {
                    break;
                } else {
                    highest.add(ea);
                }
            }
            result.putAll(ta, highest);
        }
    }

    return result;
}

From source file:org.dbpedia.spotlight.lucene.search.MergedOccurrencesContextSearcher.java

/**
 *
 * @param dbpediaResource/*from www .  ja  v a2s.c o  m*/
 * @return map from term (word) to count
 */
public List<Map.Entry<String, Integer>> getContextWords(DBpediaResource dbpediaResource)
        throws SearchException {
    Map<String, Integer> termFreqMap = new HashMap<String, Integer>();
    ScoreDoc[] docs = getHits(dbpediaResource);
    //TODO Create an exception DuplicateResourceException
    if (docs.length > 1)
        LOG.error(String.format("Resource %s has more than one document in  the index. Maybe index corrupted?",
                dbpediaResource));
    // Will accept multiple docs for a resource and get the overall top terms
    try {
        for (ScoreDoc d : docs) {
            TermFreqVector vector = mReader.getTermFreqVector(d.doc,
                    LuceneManager.DBpediaResourceField.CONTEXT.toString());
            if (vector == null)
                throw new SearchException(
                        "The index you are using does not have term frequencies stored. Cannot run getContextWords(DBpediaResource).");
            int[] freqs = vector.getTermFrequencies();
            String[] terms = vector.getTerms();
            for (int i = 0; i < vector.size(); i++) {
                termFreqMap.put(terms[i], freqs[i]);
            }
        }

    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    Ordering descOrder = new Ordering<Map.Entry<String, Integer>>() {
        public int compare(Map.Entry<String, Integer> left, Map.Entry<String, Integer> right) {
            return Ints.compare(right.getValue(), left.getValue());
        }
    };
    List<Map.Entry<String, Integer>> sorted = descOrder.sortedCopy(termFreqMap.entrySet());

    return sorted;
}

From source file:org.sonar.batch.source.SyntaxHighlightingRuleSet.java

@VisibleForTesting
protected List<SyntaxHighlightingRule> getOrderedHighlightingRules() {
    Ordering<SyntaxHighlightingRule> ruleOrdering = new Ordering<SyntaxHighlightingRule>() {
        @Override//from  ww w .jav a 2  s .c  o  m
        public int compare(@Nullable SyntaxHighlightingRule left, @Nullable SyntaxHighlightingRule right) {
            int result = 0;
            if (left != null && right != null) {
                result = left.getStartPosition() - right.getStartPosition();
                if (result == 0) {
                    result = left.getEndPosition() - right.getEndPosition();
                }
                return result;
            }
            return left != null ? 1 : -1;
        }
    };

    return ruleOrdering.sortedCopy(syntaxHighlightingRuleSet);
}

From source file:org.ms123.common.data.query.BasicSelectBuilder.java

public String getFrom(String jointype) {
    if (jointype == null) {
        jointype = "left outer join";
    }//ww  w  .  jav  a 2  s.c o m
    List<String> uniqueList = uniqueList(m_selectorList);
    Ordering<String> orderByCountDollars = new Ordering<String>() {

        public int compare(final String s1, final String s2) {
            return CharMatcher.is('$').countIn(s1) - CharMatcher.is('$').countIn(s2);
        }
    };
    List<String> sortedUniqueList = orderByCountDollars.sortedCopy(uniqueList);
    m_sortedUniqueList = sortedUniqueList;
    sortedUniqueList = checkAndCorrectList(sortedUniqueList);
    String main = sortedUniqueList.get(0);
    String clazz = m_inflector.getClassName(main);
    String from = "\"" + clazz + "\" " + main;
    for (int i = 1; i < sortedUniqueList.size(); i++) {
        String e = sortedUniqueList.get(i);
        int ind = e.lastIndexOf("$");
        String alias = null;
        if (ind != -1) {
            alias = e.substring(ind + 1);
            String join = e.substring(0, ind) + "." + e.substring(ind + 1);
            from += " " + jointype + " " + join + " " + e;
        } else {
            alias = e;
            String join = main + "." + e;
            from += " " + jointype + " " + join + " " + e;
        }
        if (hasStateSelect(alias) && !stateSelectDisabled()) {
            String state = getRequestedState();
            if (state.equals(STATE_OK) || state.equals(STATE_NEW)) {
                from += " on (" + alias + "." + STATE_FIELD + " is null or " + alias + "." + STATE_FIELD + "='"
                        + state + "')";
            } else {
                from += " on (" + alias + "." + STATE_FIELD + "='" + state + "')";
            }
        }
    }
    for (String x : sortedUniqueList) {
        debug("From:" + x);
        if (hasTeamSecurity(x)) {
            debug("BasicSelectBuilder.getFrom.selector:" + x);
            if (from.indexOf(x + "$_team_list") == -1) {
                from += " left outer join " + x + "._team_list " + x + "$_team_list";
            }
        }
    }
    return from;
}

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  w w  w  .  j ava  2  s  . c o 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: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   www.j  a  v a  2 s. c om*/
@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:org.apache.stanbol.client.enhancer.model.EnhancementStructure.java

/**
 * Returns the best {@link EntityAnnotation}s (those with the highest
 * confidence value) for each extracted {@link TextAnnotation}
 *
 * @return best annotations/*w  w  w.  jav a2  s .c o m*/
 */
public Multimap<TextAnnotation, EntityAnnotation> getBestAnnotations() {

    final Ordering<EntityAnnotation> o = new Ordering<EntityAnnotation>() {
        @Override
        public int compare(final EntityAnnotation left, final EntityAnnotation right) {
            return Doubles.compare(left.getConfidence(), right.getConfidence());
        }
    }.reverse();

    final Multimap<TextAnnotation, EntityAnnotation> result = ArrayListMultimap.create();
    for (final TextAnnotation ta : getTextAnnotations()) {
        final List<EntityAnnotation> eas = o.sortedCopy(getEntityAnnotations(ta));
        if (!eas.isEmpty()) {
            final Collection<EntityAnnotation> highest = Sets.newHashSet();
            final Double confidence = eas.get(0).getConfidence();
            for (final EntityAnnotation ea : eas) {
                if (ea.getConfidence() < confidence) {
                    break;
                } else {
                    highest.add(ea);
                }
            }
            result.putAll(ta, highest);
        }
    }

    return result;
}

From source file:io.druid.indexing.overlord.TaskLockbox.java

/**
 * Wipe out our current in-memory state and resync it from our bundled {@link io.druid.indexing.overlord.TaskStorage}.
 *///from   ww w  . j a va  2s. c o  m
public void syncFromStorage() {
    giant.lock();

    try {
        // Load stuff from taskStorage first. If this fails, we don't want to lose all our locks.
        final List<Pair<Task, TaskLock>> storedLocks = Lists.newArrayList();
        for (final Task task : taskStorage.getActiveTasks()) {
            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();
        // 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 with empty interval for task: %s", task.getId());
                continue;
            }
            activeTasks.add(task.getId());
            final Optional<TaskLock> acquiredTaskLock = tryLock(task, savedTaskLock.getInterval(),
                    Optional.of(savedTaskLock.getVersion()));
            if (acquiredTaskLock.isPresent()
                    && savedTaskLock.getVersion().equals(acquiredTaskLock.get().getVersion())) {
                taskLockCount++;
                log.info("Reacquired lock on interval[%s] version[%s] for task: %s",
                        savedTaskLock.getInterval(), savedTaskLock.getVersion(), task.getId());
            } else if (acquiredTaskLock.isPresent()) {
                taskLockCount++;
                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("Synced %,d locks for %,d activeTasks from storage (%,d locks ignored).", taskLockCount,
                activeTasks.size(), storedLocks.size() - taskLockCount);
    } finally {
        giant.unlock();
    }
}

From source file:org.geoserver.catalog.impl.DefaultCatalogFacade.java

public <T extends CatalogInfo> Iterable<T> iterable(final Class<? super T> of, final Filter filter,
        final SortBy[] sortByList) {
    List<T> all;/*  w  w w  . ja  va2s. com*/

    T t = null;
    if (NamespaceInfo.class.isAssignableFrom(of)) {
        all = (List<T>) getNamespaces();
    } else if (WorkspaceInfo.class.isAssignableFrom(of)) {
        all = (List<T>) getWorkspaces();
    } else if (StoreInfo.class.isAssignableFrom(of)) {
        all = (List<T>) getStores(of);
    } else if (ResourceInfo.class.isAssignableFrom(of)) {
        all = (List<T>) getResources(of);
    } else if (LayerInfo.class.isAssignableFrom(of)) {
        all = (List<T>) getLayers();
    } else if (LayerGroupInfo.class.isAssignableFrom(of)) {
        all = (List<T>) getLayerGroups();
    } else if (StyleInfo.class.isAssignableFrom(of)) {
        all = (List<T>) getStyles();
    } else if (MapInfo.class.isAssignableFrom(of)) {
        all = (List<T>) getMaps();
    } else {
        throw new IllegalArgumentException("Unknown type: " + of);
    }

    if (null != sortByList) {
        for (int i = sortByList.length - 1; i >= 0; i--) {
            SortBy sortBy = sortByList[i];
            Ordering<Object> ordering = Ordering.from(comparator(sortBy));
            if (SortOrder.DESCENDING.equals(sortBy.getSortOrder())) {
                ordering = ordering.reverse();
            }
            all = ordering.sortedCopy(all);
        }
    }

    if (Filter.INCLUDE.equals(filter)) {
        return all;
    }

    com.google.common.base.Predicate<T> filterAdapter = new com.google.common.base.Predicate<T>() {

        @Override
        public boolean apply(T input) {
            return filter.evaluate(input);
        }
    };

    return Iterables.filter(all, filterAdapter);
}