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

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

Introduction

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

Prototype

protected Ordering() 

Source Link

Document

Constructs a new instance of this class (only invokable by the subclass constructor, typically implicit).

Usage

From source file:com.palantir.util.Pair.java

/**
 * Returns a <code>Comparator</code> for the
 * left-hand side object of the <code>Pair</code>.
 *//*from w  w  w .j  a  v a 2  s  .c  o  m*/
public static <T extends Comparable<? super T>, V> Ordering<Pair<T, V>> compareLhSide() {
    return new Ordering<Pair<T, V>>() {
        @Override
        public int compare(Pair<T, V> o1, Pair<T, V> o2) {
            return o1.lhSide.compareTo(o2.lhSide);
        }
    };
}

From source file:brooklyn.location.cloud.CloudLocation.java

@Override
public MachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
    synchronized (mutex) {
        // Check context for entity being deployed
        Object context = flags.get(LocationConfigKeys.CALLER_CONTEXT.getName());
        if (context != null && !(context instanceof Entity)) {
            throw new IllegalStateException("Invalid location context: " + context);
        }/*from ww w  .ja  va  2 s  . c o m*/
        Entity entity = (Entity) context;

        // Look for idle CloudMachine first
        Set<Entity> idle = Sets.newTreeSet(new Ordering<Entity>() {
            @Override
            public int compare(@Nullable Entity left, @Nullable Entity right) {
                return ComparisonChain.start().compare(left.getAttribute(MachineEntity.CPU_USAGE),
                        right.getAttribute(MachineEntity.CPU_USAGE)).result();
            }
        });
        for (Entity e : getOwner().getCloudMachineList()) {
            if (Boolean.TRUE.equals(e.getAttribute(CloudMachine.SERVICE_UP))
                    && e.getAttribute(CloudMachine.ENTITY) == null) {
                idle.add(e);
            }
        }
        if (idle.size() > 0) {
            CloudMachineLocation machine = (CloudMachineLocation) Iterables.getLast(idle);
            machine.setEntity(entity);
            return machine;
        }

        // Obtain a new machine location
        MachineLocation machine = provisioner.obtain(flags);
        obtained.add(machine);

        return machine;
    }
}

From source file:org.eclipse.buildship.ui.view.task.TaskNodeViewerSorter.java

private static Ordering<TaskNode> createLexicographicalTaskOrdering() {
    return new Ordering<TaskNode>() {

        @Override//from   ww  w .  j a v a2s .  c om
        public int compare(TaskNode left, TaskNode right) {
            return left.getName().compareTo(right.getName());
        }
    };
}

From source file:org.dbpedia.spotlight.disambiguate.CustomScoresDisambiguator.java

@Override
public List<DBpediaResourceOccurrence> bestK(SurfaceFormOccurrence sfOccurrence, int k)
        throws SearchException, ItemNotFoundException {
    Set<DBpediaResource> candidates = surrogateSearcher.getCandidates(sfOccurrence.surfaceForm());

    if (candidates.size() == 0)
        return new LinkedList<DBpediaResourceOccurrence>();

    List<DBpediaResourceOccurrence> all = getScores(sfOccurrence, candidates);

    Ordering descOrder = new Ordering<DBpediaResourceOccurrence>() {
        public int compare(DBpediaResourceOccurrence left, DBpediaResourceOccurrence right) {
            return Doubles.compare(right.similarityScore(), left.similarityScore());

        }//from  w  w w . java  2  s .c  om
    };

    return descOrder.sortedCopy(all).subList(0, Math.min(k, all.size()));
}

From source file:org.apache.cassandra.tools.nodetool.TopPartitions.java

@Override
public void execute(NodeProbe probe) {
    checkArgument(args.size() == 3, "toppartitions requires keyspace, column family name, and duration");
    checkArgument(topCount < size, "TopK count (-k) option must be smaller then the summary capacity (-s)");
    String keyspace = args.get(0);
    String cfname = args.get(1);//from  ww w.j a  v a2  s. co m
    Integer duration = Integer.parseInt(args.get(2));
    // generate the list of samplers
    List<Sampler> targets = Lists.newArrayList();
    for (String s : samplers.split(",")) {
        try {
            targets.add(Sampler.valueOf(s.toUpperCase()));
        } catch (Exception e) {
            throw new IllegalArgumentException(
                    s + " is not a valid sampler, choose one of: " + join(Sampler.values(), ", "));
        }
    }

    Map<Sampler, CompositeData> results;
    try {
        results = probe.getPartitionSample(keyspace, cfname, size, duration, topCount, targets);
    } catch (OpenDataException e) {
        throw new RuntimeException(e);
    }
    boolean first = true;
    for (Entry<Sampler, CompositeData> result : results.entrySet()) {
        CompositeData sampling = result.getValue();
        // weird casting for http://bugs.sun.com/view_bug.do?bug_id=6548436
        List<CompositeData> topk = (List<CompositeData>) (Object) Lists
                .newArrayList(((TabularDataSupport) sampling.get("partitions")).values());
        Collections.sort(topk, new Ordering<CompositeData>() {
            public int compare(CompositeData left, CompositeData right) {
                return Long.compare((long) right.get("count"), (long) left.get("count"));
            }
        });
        if (!first)
            System.out.println();
        System.out.println(result.getKey().toString() + " Sampler:");
        System.out.printf("  Cardinality: ~%d (%d capacity)%n", (long) sampling.get("cardinality"), size);
        System.out.printf("  Top %d partitions:%n", topCount);
        if (topk.size() == 0) {
            System.out.println("\tNothing recorded during sampling period...");
        } else {
            int offset = 0;
            for (CompositeData entry : topk)
                offset = Math.max(offset, entry.get("string").toString().length());
            System.out.printf("\t%-" + offset + "s%10s%10s%n", "Partition", "Count", "+/-");
            for (CompositeData entry : topk)
                System.out.printf("\t%-" + offset + "s%10d%10d%n", entry.get("string").toString(),
                        entry.get("count"), entry.get("error"));
        }
        first = false;
    }
}

From source file:org.jeo.cli.JeoCLI.java

public void usage() {
    Set<String> commands = cmdr.getCommands().keySet();
    int maxLength = new Ordering<String>() {
        public int compare(String left, String right) {
            return Ints.compare(left.length(), right.length());
        };//  www  . j ava 2  s  .c  om
    }.max(commands).length();

    try {
        console.println("usage: jeo <command> [<args>]");
        console.println();
        console.println("Commands:");
        console.println();
        for (String cmd : commands) {
            console.print("\t");
            console.print(Strings.padEnd(cmd, maxLength, ' '));
            console.print("\t");
            console.println(cmdr.getCommandDescription(cmd));
        }
        console.println();
        console.println("For detailed help on a specific command use jeo <command> -h");
        console.flush();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

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}.
 *///w  ww.ja v a  2 s .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:com.android.tools.idea.npw.assetstudio.ui.PreviewIconsPanel.java

private void initializeIconComponents(@NotNull Collection<Density> densities) {
    // Sort the densities, so that we always line up icons from highest to lowest densities.
    Ordering<Density> densityOrdering = new Ordering<Density>() {
        @Override//from w  w  w. j a v  a2s.c  o m
        public int compare(Density left, Density right) {
            // The lower the enum index, the higher the density
            return Ints.compare(left.ordinal(), right.ordinal());
        }
    };

    densities = densityOrdering.immutableSortedCopy(densities);
    for (Density density : densities) {
        JPanel iconPanel = new JPanel(new VerticalFlowLayout(false, false));
        iconPanel.setBackground(myTheme.getMainColor());
        iconPanel.setOpaque(myTheme != Theme.TRANSPARENT);

        JBLabel title = new JBLabel(density.getResourceValue());
        title.setForeground(myTheme.getAltColor());
        iconPanel.add(title);

        ImageComponent iconImage = new ImageComponent(null);
        iconImage.setBorder(new LineBorder(myTheme.getAltColor()));
        iconImage.setOpaque(false);
        iconPanel.add(iconImage);

        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.PAGE_START;

        myIconsPanel.add(iconPanel, c);
        myIconImages.put(density, iconImage);
    }
}

From source file:de.hh.changeRing.initialData.InitTestData.java

private static void initTransactions() {
    if (transactions == null) {
        transactions = new Ordering<Transaction>() {
            @Override/*from  w  w w . j  a  v a 2s.  c  o m*/
            public int compare(Transaction transaction, Transaction transaction1) {
                return transaction.getDate().compareTo(transaction1.getDate());
            }
        }.sortedCopy(data.transactions);
        for (Transaction transaction : transactions) {
            process(transaction);
        }
    }
}

From source file:org.eclipse.buildship.ui.view.task.TaskNodeViewerSorter.java

private static Ordering<FaultyProjectNode> createLexicographicalFaultyProjectOrdering() {
    return new Ordering<FaultyProjectNode>() {

        @Override/*from   w ww . j a v  a2  s  .c  o m*/
        public int compare(FaultyProjectNode left, FaultyProjectNode right) {
            return left.getWorkspaceProject().get().getName()
                    .compareTo(right.getWorkspaceProject().get().getName());
        }
    };
}