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:me.lucko.luckperms.sponge.messaging.BungeeMessenger.java

@Override
public void sendOutgoingMessage(@Nonnull OutgoingMessage outgoingMessage) {
    this.plugin.getBootstrap().getSpongeScheduler().createTaskBuilder().interval(10, TimeUnit.SECONDS)
            .execute(task -> {/*from  w  w  w . j  a  v  a 2 s  . c om*/
                if (!this.plugin.getBootstrap().getGame().isServerAvailable()) {
                    return;
                }

                Collection<Player> players = this.plugin.getBootstrap().getGame().getServer()
                        .getOnlinePlayers();
                Player p = Iterables.getFirst(players, null);
                if (p == null) {
                    return;
                }

                this.channel.sendTo(p, buf -> buf.writeUTF(outgoingMessage.asEncodedString()));
                task.cancel();
            }).submit(this.plugin.getBootstrap());
}

From source file:org.apache.metron.writer.NoopWriter.java

private Function<Void, Void> getSleepFunction(String sleepConfig) {
    String usageMessage = "Unexpected: " + sleepConfig
            + " Expected value: integer for a fixed sleep duration in milliseconds (e.g. 10) "
            + "or a range of latencies separated by a comma (e.g. \"10, 20\") to sleep a random amount in that range.";
    try {//from  w  ww . ja  v  a  2s. com
        if (sleepConfig.contains(",")) {
            // random latency within a range.
            Iterable<String> it = Splitter.on(',').split(sleepConfig);
            Integer min = ConversionUtils.convert(Iterables.getFirst(it, "").trim(), Integer.class);
            Integer max = ConversionUtils.convert(Iterables.getLast(it, "").trim(), Integer.class);
            if (min != null && max != null) {
                return new RandomLatency(min, max);
            }
        } else {
            //fixed latency
            Integer latency = ConversionUtils.convert(sleepConfig.trim(), Integer.class);
            if (latency != null) {
                return new FixedLatency(latency);
            }
        }
    } catch (Throwable t) {
        throw new IllegalArgumentException(usageMessage, t);
    }
    throw new IllegalArgumentException(usageMessage);
}

From source file:nextmethod.web.razor.parser.syntaxtree.Block.java

public Span findFirstDescendentSpan() {
    SyntaxTreeNode current = this;
    while (current != null && current.isBlock()) {
        current = Iterables.getFirst(((Block) current).children, null);
    }/*from ww w  . j a  v  a2s.  c o m*/

    return typeAs(current, Span.class);
}

From source file:com.dmdirc.ui.core.aliases.CoreAliasDialogModel.java

@Override
public void loadModel() {
    for (Alias alias : aliasManager.getAliases()) {
        aliases.put(alias.getName(), alias);
        listeners.getCallable(AliasDialogModelListener.class).aliasAdded(alias);
    }/* ww w  .  ja v  a2s.c  o m*/
    setSelectedAlias(Optional.ofNullable(Iterables.getFirst(aliasManager.getAliases(), null)));
}

From source file:com.github.nethad.clustermeister.provisioning.ec2.AmazonNode.java

public String getFirstPublicAddress() {
    return Iterables.getFirst(instanceMetadata.getPublicAddresses(), null);
}

From source file:org.apache.beam.runners.spark.translation.SparkGlobalCombineFn.java

private Iterable<WindowedValue<AccumT>> createAccumulator(WindowedValue<InputT> input) {

    // sort exploded inputs.
    Iterable<WindowedValue<InputT>> sortedInputs = sortByWindows(input.explodeWindows());

    TimestampCombiner timestampCombiner = windowingStrategy.getTimestampCombiner();
    WindowFn<?, BoundedWindow> windowFn = windowingStrategy.getWindowFn();

    //--- inputs iterator, by window order.
    final Iterator<WindowedValue<InputT>> iterator = sortedInputs.iterator();
    WindowedValue<InputT> currentInput = iterator.next();
    BoundedWindow currentWindow = Iterables.getFirst(currentInput.getWindows(), null);

    // first create the accumulator and accumulate first input.
    AccumT accumulator = combineFn.createAccumulator(ctxtForInput(currentInput));
    accumulator = combineFn.addInput(accumulator, currentInput.getValue(), ctxtForInput(currentInput));

    // keep track of the timestamps assigned by the TimestampCombiner.
    Instant windowTimestamp = timestampCombiner.assign(currentWindow,
            windowingStrategy.getWindowFn().getOutputTime(currentInput.getTimestamp(), currentWindow));

    // accumulate the next windows, or output.
    List<WindowedValue<AccumT>> output = Lists.newArrayList();

    // if merging, merge overlapping windows, e.g. Sessions.
    final boolean merging = !windowingStrategy.getWindowFn().isNonMerging();

    while (iterator.hasNext()) {
        WindowedValue<InputT> nextValue = iterator.next();
        BoundedWindow nextWindow = Iterables.getOnlyElement(nextValue.getWindows());

        boolean mergingAndIntersecting = merging
                && isIntersecting((IntervalWindow) currentWindow, (IntervalWindow) nextWindow);

        if (mergingAndIntersecting || nextWindow.equals(currentWindow)) {
            if (mergingAndIntersecting) {
                // merge intersecting windows.
                currentWindow = merge((IntervalWindow) currentWindow, (IntervalWindow) nextWindow);
            }//  w  ww .java2s  .c om
            // keep accumulating and carry on ;-)
            accumulator = combineFn.addInput(accumulator, nextValue.getValue(), ctxtForInput(nextValue));
            windowTimestamp = timestampCombiner.merge(currentWindow, windowTimestamp,
                    windowingStrategy.getWindowFn().getOutputTime(nextValue.getTimestamp(), currentWindow));
        } else {
            // moving to the next window, first add the current accumulation to output
            // and initialize the accumulator.
            output.add(WindowedValue.of(accumulator, windowTimestamp, currentWindow, PaneInfo.NO_FIRING));
            // re-init accumulator, window and timestamp.
            accumulator = combineFn.createAccumulator(ctxtForInput(nextValue));
            accumulator = combineFn.addInput(accumulator, nextValue.getValue(), ctxtForInput(nextValue));
            currentWindow = nextWindow;
            windowTimestamp = timestampCombiner.assign(currentWindow,
                    windowFn.getOutputTime(nextValue.getTimestamp(), currentWindow));
        }
    }

    // add last accumulator to the output.
    output.add(WindowedValue.of(accumulator, windowTimestamp, currentWindow, PaneInfo.NO_FIRING));

    return output;
}

From source file:com.android.tools.idea.welcome.install.FirstRunWizardDefaults.java

/**
 * Returns initial SDK location. That will be the SDK location from the installer
 * handoff file in the handoff case, sdk location location from the preference if set
 * or platform-dependant default path.//from   w w  w .  j  a v  a2s  .  com
 */
@NotNull
public static File getInitialSdkLocation(@NotNull FirstRunWizardMode mode) {
    File dest = mode.getSdkLocation();
    if (dest != null) {
        return dest;
    } else {
        List<Sdk> sdks = AndroidSdks.getInstance().getAllAndroidSdks();
        Sdk sdk = Iterables.getFirst(sdks, null);
        if (sdk != null) {
            VirtualFile homeDirectory = sdk.getHomeDirectory();
            if (homeDirectory != null) {
                return VfsUtilCore.virtualToIoFile(homeDirectory);
            }
        }
        return getDefaultSdkLocation();
    }
}

From source file:com.google.template.soy.soytree.MsgSubstUnitBaseVarNameUtils.java

/**
 * The equivalent of {@code genNaiveBaseNameForExpr()} in our new algorithm for generating base
 * name.//from www.  j  a  va 2s.co  m
 *
 * Examples:    $aaaBbb -> AAA_BBB;    $aaa_bbb -> AAA_BBB;    $aaa.bbb -> BBB;    $ij.aaa -> AAA;
 * aaa.BBB -> BBB;    $aaa.0 -> AAA_0;    $aaa[0] -> AAA_0;    $aaa[0].bbb -> BBB; length($aaa) ->
 * fallback;    $aaa + 1 -> fallback
 *
 * @param exprNode The expr root of the expression to generate the shortest base name for.
 * @param fallbackBaseName The fallback base name to use if the given expression doesn't generate
 *     any base names.
 * @return The generated base name.
 */
public static String genShortestBaseNameForExpr(ExprNode exprNode, String fallbackBaseName) {

    List<String> candidateBaseNames = genCandidateBaseNamesForExpr(exprNode);
    return Iterables.getFirst(candidateBaseNames, fallbackBaseName);
}

From source file:com.opengamma.web.bundle.AbstractWebBundleResource.java

/**
 * Creates the output root data.// ww w .ja  va  2 s .  c o m
 * 
 * @return the output root data, not null
 */
protected FlexiBean createRootData() {
    FlexiBean out = getFreemarker().createRootData();
    out.put("ogStyle", new StyleTag(data()));
    out.put("ogScript", new ScriptTag(data()));
    HttpHeaders httpHeaders = data().getHttpHeaders();
    String openfin = StringUtils.EMPTY;
    if (httpHeaders != null) {
        out.put("httpHeaders", data().getHttpHeaders());
        List<String> openfinHeader = httpHeaders.getRequestHeader("x-powered-by");
        if (openfinHeader != null) {
            openfin = Iterables.getFirst(openfinHeader, StringUtils.EMPTY);
        }
    }
    out.put("openfin", openfin.toLowerCase());
    return out;
}

From source file:com.google.security.zynamics.reil.translators.ReilTranslator.java

/**
 * Returns the addresses of all basic blocks of a function. Note that the addresses are already
 * converted to REIL addresses.//from  w  w  w .  j  a  v a2s.  c o  m
 * 
 * @param function The input function.
 * 
 * @return A list of all basic block addresses of the function.
 */
private static Collection<IAddress> getBlockAddresses(final IBlockContainer<?> function) {
    return CollectionHelpers.map(function.getBasicBlocks(),
            new ICollectionMapper<ICodeContainer<?>, IAddress>() {
                private boolean isDelayedBranch(final ReilInstruction instruction) {
                    return instruction.getMnemonic().equals(ReilHelpers.OPCODE_JCC)
                            && ReilHelpers.isDelayedBranch(instruction);
                }

                @Override
                public IAddress map(final ICodeContainer<?> block) {
                    final IInstruction lastInstruction = Iterables.getFirst(block.getInstructions(), null); // getLastInstruction(block);

                    final ReilTranslator<IInstruction> translator = new ReilTranslator<IInstruction>();

                    try {
                        final ReilGraph reilGraph = translator.translate(new StandardEnvironment(),
                                lastInstruction);

                        final ReilBlock lastNode = reilGraph.getNodes().get(reilGraph.getNodes().size() - 1);

                        final ReilInstruction lastReilInstruction = Iterables
                                .getLast(lastNode.getInstructions());

                        if (isDelayedBranch(lastReilInstruction)) // If branch-delay
                        {
                            return ReilHelpers
                                    .toReilAddress(Iterables.get(block.getInstructions(), 1).getAddress());
                        } else {
                            return ReilHelpers.toReilAddress(block.getAddress());
                        }
                    } catch (final InternalTranslationException e) {
                        return ReilHelpers.toReilAddress(block.getAddress());
                    }
                }
            });
}