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.facebook.buck.cxx.CxxLinkableEnhancer.java

/**
 * @param params base params used to build the rule.  Target and deps will be overridden.
 *//*ww  w.java  2 s . c  o m*/
public static CxxLink createCxxLinkableBuildRule(CxxBuckConfig cxxBuckConfig, CxxPlatform cxxPlatform,
        BuildRuleParams params, BuildRuleResolver ruleResolver, final SourcePathResolver resolver,
        SourcePathRuleFinder ruleFinder, BuildTarget target, Path output, ImmutableList<Arg> args,
        Linker.LinkableDepType depType, Optional<Linker.CxxRuntimeType> cxxRuntimeType) {

    final Linker linker = cxxPlatform.getLd().resolve(ruleResolver);

    // Build up the arguments to pass to the linker.
    ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();

    // Add flags to generate linker map if supported.
    if (linker instanceof HasLinkerMap && LinkerMapMode.isLinkerMapEnabledForBuildTarget(target)) {
        argsBuilder.addAll(((HasLinkerMap) linker).linkerMap(output));
    }

    // Pass any platform specific or extra linker flags.
    argsBuilder.addAll(SanitizedArg.from(cxxPlatform.getCompilerDebugPathSanitizer().sanitize(Optional.empty()),
            cxxPlatform.getLdflags()));

    argsBuilder.addAll(args);

    // Add all arguments needed to link in the C/C++ platform runtime.
    Linker.LinkableDepType runtimeDepType = depType;
    if (cxxRuntimeType.orElse(Linker.CxxRuntimeType.DYNAMIC) == Linker.CxxRuntimeType.STATIC) {
        runtimeDepType = Linker.LinkableDepType.STATIC;
    }
    argsBuilder.addAll(StringArg.from(cxxPlatform.getRuntimeLdflags().get(runtimeDepType)));

    final ImmutableList<Arg> allArgs = argsBuilder.build();

    // Build the C/C++ link step.
    return new CxxLink(
            // Construct our link build rule params.  The important part here is combining the build
            // rules that construct our object file inputs and also the deps that build our
            // dependencies.
            params.copyWithChanges(target,
                    () -> FluentIterable.from(allArgs).transformAndConcat(arg -> arg.getDeps(ruleFinder))
                            .append(linker.getDeps(ruleFinder)).toSortedSet(Ordering.natural()),
                    Suppliers.ofInstance(ImmutableSortedSet.of())),
            resolver, linker, output, allArgs, cxxBuckConfig.getLinkScheduleInfo(),
            cxxBuckConfig.shouldCacheLinks());
}

From source file:org.sonar.batch.debt.IssueChangelogDebtCalculator.java

private List<FieldDiffs> technicalDebtHistory(Issue issue) {
    List<FieldDiffs> technicalDebtChangelog = changesOnField(((DefaultIssue) issue).changes());
    if (!technicalDebtChangelog.isEmpty()) {
        // Changelog have to be sorted from newest to oldest.
        // Null date should be the first as this happen when technical debt has changed since previous analysis.
        Ordering<FieldDiffs> ordering = Ordering.natural().reverse().nullsFirst()
                .onResultOf(new Function<FieldDiffs, Date>() {
                    @Override/*from w  w  w .ja v  a2s  . co m*/
                    public Date apply(FieldDiffs diff) {
                        return diff.creationDate();
                    }
                });
        return ordering.immutableSortedCopy(technicalDebtChangelog);
    }
    return Collections.emptyList();
}

From source file:me.j360.dubbo.modules.util.collection.CollectionUtil.java

/**
 * ?N, guava./*  w w w  .ja  v a 2s . c  o m*/
 */
public static <T extends Comparable> List<T> topN(Iterable<T> coll, int n) {
    return Ordering.natural().greatestOf(coll, n);
}

From source file:com.facebook.buck.jvm.java.AbstractDefaultJavaLibraryClasspaths.java

@Value.Lazy
protected ImmutableSortedSet<BuildRule> getCompileTimeClasspathFullDeps() {
    return getCompileTimeClasspathUnfilteredFullDeps().stream().filter(dep -> dep instanceof HasJavaAbi)
            .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));
}

From source file:com.facebook.buck.intellij.ideabuck.util.BuckCellFinder.java

/** Returns the {@link BuckCell} from the given canonical path. */
public Optional<BuckCell> findBuckCellFromCanonicalPath(String canonicalPath) {
    return projectSettingsProvider.getCells().filter(cell -> {
        String root = pathMacroExpander.apply(cell.getRoot());
        return canonicalPath.equals(root) || canonicalPath.startsWith(root + File.separator);
    }).max(Ordering.natural().onResultOf(cell -> cell.getRoot().length()));
}

From source file:org.dishevelled.bio.align.Alignments.java

/**
 * Return the maximum length in the specified ranges, or <code>-1</code> if ranges is empty.
 *
 * @param ranges ranges, must not be null, must not contain any null ranges, and all ranges must be [closed, open)
 * @return the maximum length in the specified ranges, or <code>-1</code> if ranges is empty
 *//* www.  j  a  va2  s  .  c  om*/
public static long maximumLength(final Iterable<Range<Long>> ranges) {
    checkNotNull(ranges);
    if (Iterables.isEmpty(ranges)) {
        return -1L;
    }
    return Ordering.natural().max(lengths(ranges));
}

From source file:org.apache.aurora.scheduler.storage.durability.Generator.java

/**
 * Generates a thrift struct of the given tuype.
 *
 * @param structClass Struct type.//from w w  w  .j  a va  2s.com
 * @param <T> Struct type.
 * @return A populated instance.
 */
static <T extends TBase<?, ?>> T newStruct(Class<T> structClass) {
    T struct;
    try {
        struct = structClass.newInstance();
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException(e);
    }

    Stream<Method> setterMethods = Stream.of(structClass.getDeclaredMethods())
            // Order methods by name for predictable behavior.  This is particularly useful for
            // deterministic behavior of picking a TUnion field.
            .sorted(Ordering.natural().onResultOf(Method::getName))
            .filter(method -> !method.getName().equals("setFieldValue"))
            .filter(method -> method.getName().startsWith("set"))
            .filter(method -> !method.getName().endsWith("IsSet"));

    if (TUnion.class.isAssignableFrom(structClass)) {
        // A TUnion can represent one of many types.  Choose one arbitrarily.
        setterMethods = setterMethods.limit(1);
    }

    setterMethods.forEach(setter -> {
        setValue(struct, setter);
    });

    return struct;
}

From source file:org.eclipse.sirius.diagram.ui.internal.operation.ComparisonHelper.java

public final void sort(List<? extends View> views) {
    /*//from  w  w  w  .  j  a v a 2s.  c  o  m
     * The main sort criterion is based on the elements' mapping's position
     * in the VSM, so that all instances of the same mapping are grouped
     * together, and if a mapping M1 appears before another M2 in the
     * specification, all instances of M1 appear before those of M2.
     */
    final List<? extends RepresentationElementMapping> allMappings = getMappingsToSort();
    Function<View, Integer> mappingIndex = new Function<View, Integer>() {
        @Override
        public Integer apply(View view) {
            if (view != null) {
                EObject element = view.getElement();
                if (element instanceof DMappingBased) {
                    RepresentationElementMapping mapping = ((DMappingBased) element).getMapping();
                    /*
                     * Use a plain indexOf search here, assuming that in
                     * practice there are never more than a handful of
                     * mappings inside a list container.
                     */
                    return allMappings.indexOf(mapping);
                }
            }
            return Integer.MAX_VALUE;
        }
    };
    /*
     * Inside a group of elements from the same mapping, use the
     * DRepresentationElement order. As opposed to the mappings, the number
     * of actual items can grow very large, so we pre-compute the elements'
     * indices with a linear scan to avoid repeated calls to indexOf for
     * each comparison.
     */
    final Map<DRepresentationElement, Integer> indices = Maps.newHashMap();
    Collection<? extends DRepresentationElement> elements = getDElementsToSort();

    int i = 0;
    for (DRepresentationElement current : elements) {
        indices.put(current, i);
        i++;
    }
    Function<View, Integer> nodeIndex = new Function<View, Integer>() {
        @Override
        public Integer apply(View view) {
            if (view != null) {
                EObject sem = ViewUtil.resolveSemanticElement(view);
                if (sem != null && indices.containsKey(sem)) {
                    return indices.get(sem);
                }
            }
            return Integer.MAX_VALUE;
        }
    };
    /*
     * Perform the actual sort, combining the two criteria above.
     */
    Collections.sort(views,
            Ordering.natural().onResultOf(mappingIndex).compound(Ordering.natural().onResultOf(nodeIndex)));
}

From source file:domainapp.dom.impl.HelloWorldObject.java

@Override
public int compareTo(final HelloWorldObject other) {
    return Ordering.natural().onResultOf(HelloWorldObject::getName).compare(this, other);
}

From source file:org.apache.druid.server.coordinator.helper.DruidCoordinatorRuleRunner.java

@Override
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params) {
    replicatorThrottler.updateParams(coordinator.getDynamicConfigs().getReplicationThrottleLimit(),
            coordinator.getDynamicConfigs().getReplicantLifetime());

    CoordinatorStats stats = new CoordinatorStats();
    DruidCluster cluster = params.getDruidCluster();

    if (cluster.isEmpty()) {
        log.warn("Uh... I have no servers. Not assigning anything...");
        return params;
    }//  w  w  w  .j  ava  2  s  .  co  m

    // find available segments which are not overshadowed by other segments in DB
    // only those would need to be loaded/dropped
    // anything overshadowed by served segments is dropped automatically by DruidCoordinatorCleanupOvershadowed
    Map<String, VersionedIntervalTimeline<String, DataSegment>> timelines = new HashMap<>();
    for (DataSegment segment : params.getAvailableSegments()) {
        VersionedIntervalTimeline<String, DataSegment> timeline = timelines.get(segment.getDataSource());
        if (timeline == null) {
            timeline = new VersionedIntervalTimeline<>(Ordering.natural());
            timelines.put(segment.getDataSource(), timeline);
        }

        timeline.add(segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(segment));
    }

    Set<DataSegment> overshadowed = new HashSet<>();
    for (VersionedIntervalTimeline<String, DataSegment> timeline : timelines.values()) {
        for (TimelineObjectHolder<String, DataSegment> holder : timeline.findOvershadowed()) {
            for (DataSegment dataSegment : holder.getObject().payloads()) {
                overshadowed.add(dataSegment);
            }
        }
    }

    Set<DataSegment> nonOvershadowed = new HashSet<>();
    for (DataSegment dataSegment : params.getAvailableSegments()) {
        if (!overshadowed.contains(dataSegment)) {
            nonOvershadowed.add(dataSegment);
        }
    }

    for (String tier : cluster.getTierNames()) {
        replicatorThrottler.updateReplicationState(tier);
    }

    DruidCoordinatorRuntimeParams paramsWithReplicationManager = params
            .buildFromExistingWithoutAvailableSegments().withReplicationManager(replicatorThrottler)
            .withAvailableSegments(nonOvershadowed).build();

    // Run through all matched rules for available segments
    DateTime now = DateTimes.nowUtc();
    MetadataRuleManager databaseRuleManager = paramsWithReplicationManager.getDatabaseRuleManager();

    final List<String> segmentsWithMissingRules = Lists.newArrayListWithCapacity(MAX_MISSING_RULES);
    int missingRules = 0;
    for (DataSegment segment : paramsWithReplicationManager.getAvailableSegments()) {
        List<Rule> rules = databaseRuleManager.getRulesWithDefault(segment.getDataSource());
        boolean foundMatchingRule = false;
        for (Rule rule : rules) {
            if (rule.appliesTo(segment, now)) {
                stats.accumulate(rule.run(coordinator, paramsWithReplicationManager, segment));
                foundMatchingRule = true;
                break;
            }
        }

        if (!foundMatchingRule) {
            if (segmentsWithMissingRules.size() < MAX_MISSING_RULES) {
                segmentsWithMissingRules.add(segment.getIdentifier());
            }
            missingRules++;
        }
    }

    if (!segmentsWithMissingRules.isEmpty()) {
        log.makeAlert("Unable to find matching rules!").addData("segmentsWithMissingRulesCount", missingRules)
                .addData("segmentsWithMissingRules", segmentsWithMissingRules).emit();
    }

    return paramsWithReplicationManager.buildFromExistingWithoutAvailableSegments().withCoordinatorStats(stats)
            .withAvailableSegments(params.getAvailableSegments()).build();
}