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

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

Introduction

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

Prototype

@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked") 
public static <C extends Comparable> Ordering<C> natural() 

Source Link

Document

Returns a serializable ordering that uses the natural order of the values.

Usage

From source file:com.sun.tools.hat.internal.server.ObjectQuery.java

private void printFullObject(JavaObject obj) {
    out.print("<h1>instance of ");
    print(obj.toString());//from   w w  w. j a  v  a2s  .co  m
    out.print(" <small>(" + obj.getSize() + " bytes)</small>");
    out.println("</h1>\n");

    out.println("<h2>Class:</h2>");
    printClass(obj.getClazz());

    out.println("<h2>Instance data members:</h2>");
    makeFieldMap(obj.getClazz().getFieldsForInstance(), obj.getFields()).entrySet().stream()
            .sorted(Ordering.natural().onResultOf(e -> e.getKey().getName())).forEach(entry -> {
                printField(entry.getKey());
                out.print(" : ");
                printThing(entry.getValue());
                out.println("<br>");
            });
}

From source file:gg.uhc.uhc.inventory.IconStack.java

@Override
public int compareTo(IconStack other) {
    return Ordering.natural().compare(weight, other.weight);
}

From source file:com.twitter.common.net.http.handlers.LogConfig.java

protected void displayPage(final HttpServletRequest req, HttpServletResponse resp, final boolean posted)
        throws ServletException, IOException {
    writeTemplate(resp, new Closure<StringTemplate>() {
        @Override// w  ww .  ja  v  a 2  s  .c om
        public void execute(StringTemplate stringTemplate) {
            LoggingMXBean logBean = LogManager.getLoggingMXBean();

            if (posted) {
                String loggerName = req.getParameter("logger");
                String loggerLevel = req.getParameter("level");
                if (loggerName != null && loggerLevel != null) {
                    Logger logger = Logger.getLogger(loggerName);
                    Level newLevel = loggerLevel.equals("INHERIT") ? null : Level.parse(loggerLevel);
                    logger.setLevel(newLevel);
                    if (newLevel != null) {
                        maybeAdjustHandlerLevels(logger, newLevel);
                    }

                    stringTemplate.setAttribute("configChange",
                            String.format("%s level changed to %s", loggerName, loggerLevel));
                }
            }

            List<LoggerConfig> loggerConfigs = Lists.newArrayList();
            for (String logger : Ordering.natural().immutableSortedCopy(logBean.getLoggerNames())) {
                loggerConfigs.add(new LoggerConfig(logger, logBean.getLoggerLevel(logger)));
            }

            stringTemplate.setAttribute("loggers", loggerConfigs);
            stringTemplate.setAttribute("levels", LOG_LEVELS);
        }
    });
}

From source file:org.apache.druid.timeline.VersionedIntervalTimeline.java

public static VersionedIntervalTimeline<String, DataSegment> forSegments(Iterator<DataSegment> segments) {
    final VersionedIntervalTimeline<String, DataSegment> timeline = new VersionedIntervalTimeline<>(
            Ordering.natural());
    addSegments(timeline, segments);/*from w  w w  .  ja  v a2 s .  c o  m*/
    return timeline;
}

From source file:me.taylorkelly.mywarp.util.MatchList.java

/**
 * Gets a naturally sorted immutable list that contains all warps matching this Matchers criteria.
 *
 * @return a list of all matches//from www .  java  2  s  .  c o m
 */
public ImmutableList<Warp> getMatches() {
    return Ordering.natural().immutableSortedCopy(matchingWarps);
}

From source file:org.onosproject.cli.net.PartitionsListCommand.java

/**
 * Displays partition client info as text.
 *
 * @param partitionClientInfo partition client information
 *///from  ww w. j  a v  a2s .c  o m
private void displayPartitionClients(List<PartitionClientInfo> partitionClientInfo) {
    if (partitionClientInfo.isEmpty()) {
        return;
    }
    ClusterService clusterService = get(ClusterService.class);
    print("-------------------------------------------------------------------");
    print(CLIENT_FMT, "Name", "SessionId", "Status", "Servers");
    print("-------------------------------------------------------------------");

    for (PartitionClientInfo info : partitionClientInfo) {
        boolean first = true;
        for (NodeId serverId : Ordering.natural().sortedCopy(info.servers())) {
            ControllerNode server = clusterService.getNode(serverId);
            String serverString = String.format("%s:%d", server.id(), server.tcpPort());
            if (first) {
                print(CLIENT_FMT, info.partitionId(), info.sessionId(), info.status(), serverString);
                first = false;
            } else {
                print(CLIENT_FMT, "", "", "", serverString);
            }
        }
        if (!first) {
            print("-------------------------------------------------------------------");
        }
    }
}

From source file:com.facebook.buck.rules.query.QueryUtils.java

private static ImmutableSortedSet<BuildTarget> resolveDepQuery(BuildTarget target, Query query,
        QueryCache cache, ActionGraphBuilder graphBuilder, CellPathResolver cellRoots, TargetGraph targetGraph,
        ImmutableSet<BuildTarget> declaredDeps) {
    GraphEnhancementQueryEnvironment env = new GraphEnhancementQueryEnvironment(Optional.of(graphBuilder),
            Optional.of(targetGraph), TYPE_COERCER_FACTORY, cellRoots, UNCONFIGURED_BUILD_TARGET_FACTORY,
            target.getBaseName(), declaredDeps, target.getTargetConfiguration());
    try {// ww w.  j a va  2s.  com
        QueryExpression parsedExp = QueryExpression.parse(query.getQuery(), env);
        Set<QueryTarget> queryTargets = cache.getQueryEvaluator(targetGraph).eval(parsedExp, env);
        return queryTargets.stream().map(queryTarget -> {
            Preconditions.checkState(queryTarget instanceof QueryBuildTarget);
            return ((QueryBuildTarget) queryTarget).getBuildTarget();
        }).collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));
    } catch (QueryException e) {
        if (e.getCause() instanceof InterruptedException) {
            Threads.interruptCurrentThread();
        }
        throw new RuntimeException("Error parsing/executing query from deps for " + target, e);
    }
}

From source file:lib.security.ServerRestInterfaceRealm.java

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    // the current user has been previously loaded via doGetAuthenticationInfo before, use those permissions
    User user = UserService.current();//from  w w w .j a v  a2  s . co  m
    if (!principals.getPrimaryPrincipal().equals(user.getName())) {
        log.info("retrieving loaded user {} from per-request user cache", principals.getPrimaryPrincipal());
        user = (User) Http.Context.current().args
                .get("perRequestUsersCache:" + principals.getPrimaryPrincipal().toString());
        if (user == null) {
            log.error(
                    "Cannot find previously loaded user, need to load it explicitely. This is unimplemented.");
            return null;
        }
    }
    final List<String> permissions = user.getPermissions();
    final SimpleAuthorizationInfo authzInfo = new SimpleAuthorizationInfo();
    if (log.isTraceEnabled()) {
        log.trace("Permissions for {} are {}", user.getName(),
                Ordering.natural().sortedCopy(user.getPermissions()));
    }
    authzInfo.setStringPermissions(Sets.newHashSet(permissions));
    return authzInfo;
}

From source file:org.apache.ctakes.relationextractor.ae.IdentifiedAnnotationExpander.java

public static String getEnclosingNP(JCas jCas, IdentifiedAnnotation identifiedAnnotation) {

    // map each covering treebank node to its character length
    Map<TreebankNode, Integer> treebankNodeSizes = new HashMap<TreebankNode, Integer>();
    for (TreebankNode treebankNode : JCasUtil.selectCovering(jCas, TreebankNode.class,
            identifiedAnnotation.getBegin(), identifiedAnnotation.getEnd())) {

        // only expand nouns (and not verbs or adjectives)
        if (treebankNode instanceof TerminalTreebankNode) {
            if (!treebankNode.getNodeType().startsWith("N")) {
                return identifiedAnnotation.getCoveredText();
            }//w w  w . j a  v a  2 s  .c  o m
        }

        // because only nouns are expanded, look for covering NPs
        if (treebankNode.getNodeType().equals("NP")) {
            treebankNodeSizes.put(treebankNode, treebankNode.getCoveredText().length());
        }
    }

    // find the shortest covering treebank node
    List<TreebankNode> sortedTreebankNodes = new ArrayList<TreebankNode>(treebankNodeSizes.keySet());
    Function<TreebankNode, Integer> getValue = Functions.forMap(treebankNodeSizes);
    Collections.sort(sortedTreebankNodes, Ordering.natural().onResultOf(getValue));

    if (sortedTreebankNodes.size() > 0) {
        return sortedTreebankNodes.get(0).getCoveredText();
    }

    return identifiedAnnotation.getCoveredText();
}

From source file:com.google.devtools.build.lib.rules.config.ConfigFeatureFlagTaggedTrimmingTransitionFactory.java

@Override
public PatchTransition buildTransitionFor(Rule rule) {
    NonconfigurableAttributeMapper attrs = NonconfigurableAttributeMapper.of(rule);
    RuleClass ruleClass = rule.getRuleClassObject();
    if (ruleClass.getName().equals(ConfigRuleClasses.ConfigFeatureFlagRule.RULE_NAME)) {
        return new ConfigFeatureFlagTaggedTrimmingTransition(ImmutableSortedSet.of(rule.getLabel()));
    }// ww w.  jav a 2 s .c o m

    ImmutableSortedSet.Builder<Label> requiredLabelsBuilder = new ImmutableSortedSet.Builder<>(
            Ordering.natural());
    if (attrs.isAttributeValueExplicitlySpecified(attributeName)
            && !attrs.get(attributeName, NODEP_LABEL_LIST).isEmpty()) {
        requiredLabelsBuilder.addAll(attrs.get(attributeName, NODEP_LABEL_LIST));
    }
    if (ruleClass.getTransitionFactory() instanceof ConfigFeatureFlagTransitionFactory) {
        String settingAttribute = ((ConfigFeatureFlagTransitionFactory) ruleClass.getTransitionFactory())
                .getAttributeName();
        // Because the process of setting a flag also creates a dependency on that flag, we need to
        // include all the set flags, even if they aren't actually declared as used by this rule.
        requiredLabelsBuilder.addAll(attrs.get(settingAttribute, LABEL_KEYED_STRING_DICT).keySet());
    }

    ImmutableSortedSet<Label> requiredLabels = requiredLabelsBuilder.build();
    if (requiredLabels.isEmpty()) {
        return ConfigFeatureFlagTaggedTrimmingTransition.EMPTY;
    }

    return new ConfigFeatureFlagTaggedTrimmingTransition(requiredLabels);
}