Example usage for com.google.common.collect Iterables getFirst

List of usage examples for com.google.common.collect Iterables getFirst

Introduction

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

Prototype

@Nullable
public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) 

Source Link

Document

Returns the first element in iterable or defaultValue if the iterable is empty.

Usage

From source file:com.google.idea.blaze.java.run.RunUtil.java

/**
 * @return The Blaze test rule containing the target test class. In the case of multiple
 * containing rules, the first rule sorted alphabetically by label.
 *///from ww w . j a  va  2  s.c o  m
@Nullable
public static RuleIdeInfo ruleForTestClass(@NotNull Project project, @NotNull PsiClass testClass,
        @Nullable TestIdeInfo.TestSize testSize) {
    File testFile = getFileForClass(testClass);
    if (testFile == null) {
        return null;
    }
    TestRuleFinder testRuleFinder = TestRuleFinder.getInstance(project);
    // We don't expose multiple rule choices, just pick first
    Label testLabel = Iterables.getFirst(testRuleFinder.testTargetsForSourceFile(testFile, testSize), null);
    if (testLabel == null) {
        return null;
    }
    return RuleFinder.getInstance().ruleForTarget(project, testLabel);
}

From source file:tds.student.performance.utils.InitializeSegmentsHelper.java

public static Integer minimumSegmentPosition(List<OpportunitySegmentInsert> segmentList) {

    OpportunitySegmentInsert minimumPosition = Iterables.getFirst(
            Ordering.natural().nullsLast().onResultOf(new Function<OpportunitySegmentInsert, Integer>() {
                public Integer apply(OpportunitySegmentInsert segment) {
                    return segment.getSegmentPosition();
                }/*from   www .j  a  va 2s .c  o m*/
            }).sortedCopy(segmentList), null);

    return minimumPosition == null ? null : minimumPosition.getSegmentPosition();
}

From source file:io.wcm.caravan.pipeline.extensions.hal.crawler.OutputProcessors.java

/**
 * Creates a flat Collection of HAL links for each processed request.
 * @return Output processor creating flat links collection
 *//*from   w ww  .jav  a 2s  .  c o  m*/
public static OutputProcessor report() {
    return new OutputProcessor() {

        @Override
        public JsonPipelineOutput process(JsonPipelineOutput previousStepOutput,
                List<JsonPipelineOutput> loadedLinkOutputs) {

            // create output HAL
            String url = getUrl(previousStepOutput);
            HalResource hal = new HalResource(url);

            // add URL with relation to links
            CaravanHttpRequest request = getRequest(previousStepOutput);
            if (request != null && request.getHeaders().containsKey(HalCrawler.HEADER_CRAWLER_RELATION)) {
                String relation = Iterables
                        .getFirst(request.getHeaders().get(HalCrawler.HEADER_CRAWLER_RELATION), null);
                hal.addLinks(relation, new Link(url));
            }

            // add child links
            loadedLinkOutputs.stream().map(loadedLinkOutput -> new HalResource(loadedLinkOutput.getPayload()))
                    .flatMap(loadedLinkHal -> loadedLinkHal.getLinks().entries().stream())
                    .filter(entry -> !"self".equals(entry.getKey()))
                    .forEach(entry -> hal.addLinks(entry.getKey(), entry.getValue()));

            // output
            return previousStepOutput.withPayload(hal.getModel());
        }

        @Override
        public String getId() {
            return "REPORT";
        }

    };
}

From source file:org.jpmml.lightgbm.Section.java

public String id() {
    Map.Entry<String, String> entry = Iterables.getFirst(entrySet(), null);

    if (entry == null) {
        throw new IllegalStateException();
    }/* ww  w .  j  a va2s. com*/

    String key = entry.getKey();
    String value = entry.getValue();

    return (value != null ? (key + "=" + value) : key);
}

From source file:org.apache.hadoop.metrics2.impl.MetricsRecords.java

private static AbstractMetric getFirstMetricByName(MetricsRecord record, String name) {
    return Iterables.getFirst(Iterables.filter(record.metrics(), new AbstractMetricPredicate(name)), null);
}

From source file:org.opennms.smoketest.utils.DaoUtils.java

@SuppressWarnings("unchecked")
public static <T> Callable<T> findMatchingCallable(OnmsDao<?, ?> dao, Criteria criteria) {
    return () -> (T) Iterables.getFirst(dao.findMatching(criteria), null);
}

From source file:org.opendaylight.mdsal.binding.javav2.generator.impl.util.YangTextTemplate.java

public static String formatSchemaPath(final String moduleName, final Iterable<QName> schemaPath) {
    final StringBuilder sb = new StringBuilder();
    sb.append(moduleName);/*  www  .  j  a v a  2s. c  o  m*/

    QName currentElement = Iterables.getFirst(schemaPath, null);
    for (QName pathElement : schemaPath) {
        sb.append('/');
        if (!currentElement.getNamespace().equals(pathElement.getNamespace())) {
            currentElement = pathElement;
            sb.append(pathElement);
        } else {
            sb.append(pathElement.getLocalName());
        }
    }
    return sb.toString();
}

From source file:com.android.tools.idea.npw.importing.ImportUIUtil.java

/**
 * Formats a message picking the format string depending on number of arguments
 *
 * @param values                       values that will be used as format argument.
 * @param oneElementMessage            message when only one value is in the list. Should accept one string argument.
 * @param twoOrThreeElementsMessage    message format when there's 2 or 3 values. Should accept two string arguments.
 * @param moreThenThreeElementsMessage message format for over 3 values. Should accept one string and one number.
 * @return formatted message string/* www .j a v a 2  s .c o  m*/
 */
public static String formatElementListString(Iterable<String> values, String oneElementMessage,
        String twoOrThreeElementsMessage, String moreThenThreeElementsMessage) {
    int size = Iterables.size(values);
    if (size <= 1) { // If there's 0 elements, some error happened
        return String.format(oneElementMessage, Iterables.getFirst(values, "<validation error>"));
    } else if (size <= 3) {
        return String.format(twoOrThreeElementsMessage, atMostTwo(values, size), Iterables.getLast(values));
    } else {
        return String.format(moreThenThreeElementsMessage, atMostTwo(values, size), size - 2);
    }
}

From source file:com.facebook.buck.apple.xcode.FrameworkPath.java

public static FrameworkPath fromString(BuildTarget target, String string) {
    Path path = Paths.get(string);

    String firstElement = Preconditions.checkNotNull(Iterables.getFirst(path, Paths.get(""))).toString();

    if (firstElement.startsWith("$")) { // NOPMD - length() > 0 && charAt(0) == '$' is ridiculous
        Optional<PBXReference.SourceTree> sourceTree = PBXReference.SourceTree.fromBuildSetting(firstElement);
        if (sourceTree.isPresent()) {
            return ImmutableFrameworkPath.builder()
                    .sourceTreePath(new SourceTreePath(sourceTree.get(), path.subpath(1, path.getNameCount())))
                    .build();//from  ww w .  j  ava 2 s.c o  m
        } else {
            throw new HumanReadableException(String.format(
                    "Unknown SourceTree: %s in target: %s. Should be one of: %s", firstElement, target,
                    Joiner.on(',')
                            .join(Iterables.transform(ImmutableList.copyOf(PBXReference.SourceTree.values()),
                                    new Function<PBXReference.SourceTree, String>() {
                                        @Override
                                        public String apply(PBXReference.SourceTree input) {
                                            return "$" + input.toString();
                                        }
                                    }))));
        }
    } else {
        return ImmutableFrameworkPath.builder().sourcePath(new BuildTargetSourcePath(target, Paths.get(string)))
                .build();
    }
}

From source file:org.apache.metron.statistics.sampling.SamplerUtil.java

public Sampler merge(Iterable<Sampler> samplers, Optional<Sampler> baseSampler) {
    if (Iterables.isEmpty(samplers)) {
        return null;
    }/*  w  w  w . j av a  2  s  . c o m*/
    Sampler ret = baseSampler.orElse(Iterables.getFirst(samplers, null).cloneEmpty());
    for (Sampler s : samplers) {
        ret.addAll(s.get());
    }
    return ret;
}