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

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

Introduction

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

Prototype

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

Source Link

Document

Returns the last element of iterable or defaultValue if the iterable is empty.

Usage

From source file:com.jeroensteenbeeke.andalite.java.transformation.operations.impl.EnsureEndReturnStatement.java

@Override
public List<Transformation> perform(IBodyContainer input) throws OperationException {
    if (input.isAbstract()) {
        throw new OperationException("Cannot insert statement into abstract method!");
    }/*from  ww  w  .j av a  2s  . com*/

    AnalyzedStatement last = Iterables.getLast(input.getStatements(), null);

    if (last == null) {
        // No statements
        return ImmutableList.of(Transformation.insertAt(input.getLocation().getEnd() - 1,
                String.format("\t\treturn %s;\n", returnValue)));
    } else {
        // One or more statements
        if (last instanceof ReturnStatement) {
            // Check if return statement matches expectations
            ReturnStatement statement = (ReturnStatement) last;

            AnalyzedExpression returnExpression = statement.getReturnExpression();
            if (!returnExpression.toJavaString().equals(returnValue)) {
                return ImmutableList.of(Transformation.replace(returnExpression, returnValue));
            }
        } else {
            // Insert return statement after
            return ImmutableList
                    .of(Transformation.insertAfter(last, String.format("\t\treturn %s;", returnValue)));
        }
    }

    return ImmutableList.of();
}

From source file:nextmethod.web.razor.parser.internal.MarkupCollapser.java

@Override
protected SyntaxTreeNode rewriteSpan(@Nonnull final BlockBuilder parent, @Nonnull final Span span) {
    // Only rewrite if we have a previous that is also markup (canRewrite does this check for us!)
    final Span previous = typeAs(Iterables.getLast(parent.getChildren(), null), Span.class);
    if (previous == null || !canRewrite(previous)) {
        return span;
    }/*from  w w w. j av a  2s. c om*/

    // Merge spans
    parent.getChildren().remove(previous);
    final SpanBuilder merged = new SpanBuilder();
    fillSpan(merged, previous.getStart(), previous.getContent() + span.getContent());
    return merged.build();
}

From source file:org.opendaylight.controller.sal.dom.broker.impl.DataReaderRouter.java

@Override
protected CompositeNodeTOImpl merge(final YangInstanceIdentifier path, final Iterable<CompositeNode> data) {
    PathArgument pathArgument = Iterables.getLast(path.getPathArguments(), null);
    boolean empty = true;
    QName name = (pathArgument == null ? null : pathArgument.getNodeType());
    final ArrayList<Node<?>> nodes = new ArrayList<Node<?>>();
    final HashMap<QName, SimpleNode<?>> keyNodes = new HashMap<QName, SimpleNode<?>>();
    for (final CompositeNode dataBit : data) {
        try {/*from w w w . jav a2  s  . c  om*/
            if (pathArgument != null && dataBit != null) {
                empty = false;
                final Map<QName, SimpleNode<?>> keyNodesLocal = getKeyNodes(pathArgument, dataBit);
                nodes.addAll(this.childrenWithout(dataBit, keyNodesLocal.entrySet()));
            } else if (dataBit != null) {
                empty = false;
                nodes.addAll(dataBit.getValue());
            }
        } catch (IllegalStateException e) {
            LOG.error("BUG: Readed data for path {} was invalid", path, e);
        }
    }
    if (empty) {
        return null;
    }
    /**
     * Reading from Root
     *
     */
    if (pathArgument == null) {
        return new CompositeNodeTOImpl(NETCONF_DATA, null, nodes);
    }
    final ArrayList<Node<?>> finalNodes = new ArrayList<Node<?>>(nodes.size() + keyNodes.size());
    finalNodes.addAll(keyNodes.values());
    finalNodes.addAll(nodes);
    return new CompositeNodeTOImpl(name, null, finalNodes);
}

From source file:org.apache.james.mailbox.quota.model.QuotaThresholdHistory.java

public HistoryEvolution compareWithCurrentThreshold(QuotaThresholdChange thresholdChange,
        Duration gracePeriod) {//from   ww  w  .j av  a2 s . c  o  m
    Optional<QuotaThreshold> lastThreshold = Optional.ofNullable(Iterables.getLast(changes, null))
            .map(QuotaThresholdChange::getQuotaThreshold);

    return compareWithCurrentThreshold(thresholdChange, gracePeriod, lastThreshold.orElse(QuotaThreshold.ZERO));
}

From source file:org.apache.metron.enrichment.bolt.HBaseBolt.java

public static String zkConnectStringToPort(String connString) {
    String hostPortPair = Iterables.getFirst(Splitter.on(",").split(connString), "");
    return Iterables.getLast(Splitter.on(":").split(hostPortPair), DEFAULT_ZK_PORT);
}

From source file:org.eclipse.osee.orcs.db.internal.sql.SqlAliasManager.java

public String getLastAlias(int level, AliasEntry table, ObjectType objectType) {
    Collection<String> aliases = getAliases(level, table, objectType);
    return Iterables.getLast(aliases, null);
}

From source file:com.spotify.styx.cli.PrettyCliOutput.java

@Override
public void printStates(RunStateDataPayload runStateDataPayload) {
    System.out.println(String.format("  %-20s %-12s %-47s %-7s %s", "WORKFLOW INSTANCE", "STATE",
            "LAST EXECUTION ID", "TRIES", "PREVIOUS EXECUTION MESSAGE"));

    CliUtil.groupStates(runStateDataPayload.activeStates()).entrySet().forEach(entry -> {
        System.out.println();/*  w w  w .  jav a  2 s .  c  om*/
        System.out.println(String.format("%s %s", colored(CYAN, entry.getKey().componentId()),
                colored(BLUE, entry.getKey().id())));
        entry.getValue().forEach(runStateData -> {
            final StateData stateData = runStateData.stateData();
            final Ansi ansiState = getAnsiForState(runStateData);

            final Message lastMessage = Iterables.getLast(stateData.messages(),
                    Message.create(Message.MessageLevel.UNKNOWN, "No info"));
            final Ansi ansiMessage = colored(messageColor(lastMessage.level()), lastMessage.line());

            System.out.println(String.format("  %-20s %-20s %-47s %-7d %s",
                    runStateData.workflowInstance().parameter(), ansiState,
                    stateData.executionId().orElse("<no-execution-id>"), stateData.tries(), ansiMessage));
        });
    });
}

From source file:io.crate.execution.dsl.phases.JoinPhase.java

JoinPhase(UUID jobId, int executionNodeId, String name, List<Projection> projections,
        @Nullable MergePhase leftMergePhase, @Nullable MergePhase rightMergePhase, int numLeftOutputs,
        int numRightOutputs, Collection<String> executionNodes, JoinType joinType,
        @Nullable Symbol joinCondition) {
    super(jobId, executionNodeId, name, projections);
    Projection lastProjection = Iterables.getLast(projections, null);
    assert lastProjection != null : "lastProjection must not be null";
    assert joinCondition == null || !SymbolVisitors.any(Symbols.IS_COLUMN,
            joinCondition) : "joinCondition must not contain columns: " + joinCondition;
    outputTypes = Symbols.typeView(lastProjection.outputs());
    this.leftMergePhase = leftMergePhase;
    this.rightMergePhase = rightMergePhase;
    this.numLeftOutputs = numLeftOutputs;
    this.numRightOutputs = numRightOutputs;
    this.executionNodes = executionNodes;
    this.joinType = joinType;
    this.joinCondition = joinCondition;
}

From source file:com.android.tools.idea.avdmanager.AvdConfigurationOptionHelpPanel.java

public void setDescriptionText(@Nullable String descriptionText) {
    if (descriptionText == null || descriptionText.isEmpty()) {
        ((CardLayout) myContentPanel.getLayout()).show(myContentPanel, "NothingSelected");
    } else {/* w  ww .  j  a  v  a 2s .c om*/
        ((CardLayout) myContentPanel.getLayout()).show(myContentPanel, "Info");
        Iterable<String> iterable = Splitter.on('|').split(descriptionText);
        myTitle.setText("<html>" + Iterables.getFirst(iterable, null) + "</html>");
        myDescription.setText("<html>" + Iterables.getLast(iterable, null) + "</html>");
    }
    Window window = SwingUtilities.getWindowAncestor(this);
    if (window != null) {
        window.pack();
    }
}

From source file:io.crate.planner.node.dql.join.NestedLoopPhase.java

public NestedLoopPhase(UUID jobId, int executionNodeId, String name, List<Projection> projections,
        @Nullable MergePhase leftMergePhase, @Nullable MergePhase rightMergePhase,
        Collection<String> executionNodes, JoinType joinType, @Nullable Symbol joinCondition,
        int numLeftOutputs, int numRightOutputs) {
    super(jobId, executionNodeId, name, projections);
    Projection lastProjection = Iterables.getLast(projections, null);
    assert lastProjection != null;
    outputTypes = Symbols.extractTypes(lastProjection.outputs());
    this.leftMergePhase = leftMergePhase;
    this.rightMergePhase = rightMergePhase;
    this.executionNodes = executionNodes;
    this.joinType = joinType;
    this.joinCondition = joinCondition;
    this.numLeftOutputs = numLeftOutputs;
    this.numRightOutputs = numRightOutputs;
}