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

public static <T> T getLast(Iterable<T> iterable) 

Source Link

Document

Returns the last element of iterable .

Usage

From source file:org.sonar.javascript.checks.ExpressionComplexityCheck.java

@Override
public void leaveNode(Tree tree) {
    if (tree.is(CONDITIONAL_EXPRS)) {
        ExpressionComplexity currentExpression = Iterables.getLast(statementLevel);
        currentExpression.decrementNestedExprLevel();

        if (currentExpression.isOnFirstExprLevel()) {
            List<SyntaxToken> complexityOperators = currentExpression.getComplexityOperators();

            if (complexityOperators.size() > max) {
                addIssue(tree, complexityOperators);
            }/*w  ww. ja va  2s  . com*/
            currentExpression.resetExpressionComplexityOperators();
        }

    } else if (tree.is(SCOPES)) {
        statementLevel.remove(statementLevel.size() - 1);
    }
}

From source file:org.graylog2.shared.buffers.processors.DecodingProcessor.java

private void processMessage(final MessageEvent event) throws ExecutionException {
    final RawMessage raw = event.getRaw();

    final Codec.Factory<? extends Codec> factory = codecFactory.get(raw.getCodecName());
    if (factory == null) {
        LOG.warn("Couldn't find factory for codec {}, skipping message.", raw.getCodecName());
        return;//from  w  w w  .  ja  v a 2  s. c o m
    }

    final Codec codec = factory.create(raw.getCodecConfig());

    // for backwards compatibility: the last source node should contain the input we use.
    // this means that extractors etc defined on the prior inputs are silently ignored.
    // TODO fix the above
    String inputIdOnCurrentNode;
    try {
        // .inputId checked during raw message decode!
        inputIdOnCurrentNode = Iterables.getLast(raw.getSourceNodes()).inputId;
    } catch (NoSuchElementException e) {
        inputIdOnCurrentNode = null;
    }
    final String baseMetricName = name(codec.getClass(), inputIdOnCurrentNode);

    Message message = null;
    Collection<Message> messages = null;

    final Timer.Context decodeTimeCtx = parseTime.time();
    final long decodeTime;
    try {
        // This is ugly but needed for backwards compatibility of the Codec interface in 1.x.
        // TODO The Codec interface should be changed for 2.0 to support collections of messages so we can remove this hack.
        if (codec instanceof MultiMessageCodec) {
            messages = ((MultiMessageCodec) codec).decodeMessages(raw);
        } else {
            message = codec.decode(raw);
        }
    } catch (RuntimeException e) {
        String remote = "unknown source";
        final ResolvableInetSocketAddress remoteAddress = raw.getRemoteAddress();
        if (remoteAddress != null) {
            remote = remoteAddress.getInetSocketAddress().toString();
        }
        LOG.error("Unable to decode raw message {} (journal offset {}) encoded as {} received from {}.",
                raw.getId(), raw.getJournalOffset(), raw.getCodecName(), remote);
        metricRegistry.meter(name(baseMetricName, "failures")).mark();
        throw e;
    } finally {
        decodeTime = decodeTimeCtx.stop();
    }

    if (message != null) {
        event.setMessage(
                postProcessMessage(raw, codec, inputIdOnCurrentNode, baseMetricName, message, decodeTime));
    } else if (messages != null && !messages.isEmpty()) {
        final List<Message> processedMessages = Lists.newArrayListWithCapacity(messages.size());

        for (final Message msg : messages) {
            final Message processedMessage = postProcessMessage(raw, codec, inputIdOnCurrentNode,
                    baseMetricName, msg, decodeTime);

            if (processedMessage != null) {
                processedMessages.add(processedMessage);
            }
        }

        event.setMessages(processedMessages);
    }
}

From source file:org.sosy_lab.cpachecker.cpa.bam.ARGSubtreeRemover.java

void removeSubtree(ARGReachedSet mainReachedSet, ARGPath pPath, ARGState element,
        List<Precision> pNewPrecisions, List<Predicate<? super Precision>> pNewPrecisionTypes,
        Map<ARGState, ARGState> pPathElementToReachedState) {

    List<ARGState> path = trimPath(pPath, element);
    assert path.get(path.size() - 1).equals(element);
    assert path.size() >= 2; // extreme case of length 2: [root, target]

    List<ARGState> relevantCallNodes = getRelevantDefinitionNodes(path);
    assert path.containsAll(relevantCallNodes) : "only nodes of path are relevant";
    assert relevantCallNodes.get(0) == path.get(0) : "root should be relevant";
    assert relevantCallNodes.size() >= 1 : "at least the main-function should be open at the target-state";

    Set<Pair<ARGState, ARGState>> neededRemoveCachedSubtreeCalls = new LinkedHashSet<>();

    //iterate from root to element and remove all subtrees for subgraph calls
    for (int i = 0; i < relevantCallNodes.size() - 1; i++) { // ignore root and the last element
        final ARGState pathElement = relevantCallNodes.get(i);
        final ARGState nextElement = relevantCallNodes.get(i + 1);
        neededRemoveCachedSubtreeCalls.add(Pair.of(pPathElementToReachedState.get(pathElement),
                pPathElementToReachedState.get(nextElement)));
    }//from   ww w  . j  av a  2  s.co  m

    if (bamCache.doesAggressiveCaching()) {
        ensureExactCacheHitsOnPath(mainReachedSet, pPath, element, pNewPrecisions, pPathElementToReachedState,
                neededRemoveCachedSubtreeCalls);
    }

    final ARGState lastRelevantNode = pPathElementToReachedState.get(Iterables.getLast(relevantCallNodes));
    final ARGState target = pPathElementToReachedState.get(element);
    for (final Pair<ARGState, ARGState> removeCachedSubtreeArguments : neededRemoveCachedSubtreeCalls) {
        final List<Precision> newPrecisions;
        if (removeCachedSubtreeArguments.getSecond() == lastRelevantNode) { // last iteration
            newPrecisions = pNewPrecisions;
        } else {
            ReachedSet nextReachedSet = abstractStateToReachedSet.get(removeCachedSubtreeArguments.getSecond());
            assert nextReachedSet != null : "call-state does not match reachedset";
            if (target.getParents().contains(nextReachedSet.getFirstState())) {
                newPrecisions = pNewPrecisions;
            } else {
                newPrecisions = null; // ignore newPrecisions for all iterations except the last one
            }
        }
        removeCachedSubtree(removeCachedSubtreeArguments.getFirst(), removeCachedSubtreeArguments.getSecond(),
                newPrecisions, pNewPrecisionTypes);
    }

    removeCachedSubtree(pPathElementToReachedState.get(Iterables.getLast(relevantCallNodes)),
            pPathElementToReachedState.get(element), pNewPrecisions, pNewPrecisionTypes);

    // the main-reachedset contains only the root, exit-states and targets.
    // we assume, that the current refinement was caused by a target-state.
    final ARGState lastState = (ARGState) mainReachedSet.asReachedSet().getLastState();
    assert lastState.isTarget();
    mainReachedSet.removeSubtree(lastState);
}

From source file:org.sosy_lab.cpachecker.cpa.value.refiner.utils.AssumptionUseDefinitionCollector.java

/**
 * This method collects the respective referenced variables in the given path.
 *
 * @param path the path to analyze//from ww w  .j a v  a 2  s. c om
 * @return the mapping of location to referenced variables in the given path
 */
public Set<String> obtainUseDefInformation(List<CFAEdge> path) {

    dependingVariables.clear();
    collectedVariables.clear();

    determineGlobalVariables(path);

    for (int i = path.size() - 1; i >= 0; i--) {
        CFAEdge edge = path.get(i);
        collectVariables(edge, collectedVariables);

        if (Iterables.getLast(path).getEdgeType() == CFAEdgeType.AssumeEdge && dependingVariables.isEmpty()) {
            dependenciesResolvedOffset = i;
            return collectedVariables;
        }
    }

    // for full paths, the set of depending variables always has be empty at this point,
    // but sometimes, the use-def information is derived from incomplete paths,
    // and for those it can happen that not all depending variables are consumed
    // disabled again, because handling for pointers is incomplete
    // assert dependingVariables.size() == 0 || isIncompletePath(path);

    // add the remaining depending variables to the set of collectedVariables
    collectedVariables.addAll(dependingVariables);

    return collectedVariables;
}

From source file:org.obm.push.mail.imap.MailboxTestUtils.java

public Email emailInMailbox(String mailboxName) throws MailException {
    Set<Email> emailsFromInbox = mailboxEmails(mailboxName);
    return Iterables.getLast(emailsFromInbox);
}

From source file:com.google.errorprone.bugpatterns.TypeParameterUnusedInFormals.java

private Description attemptFix(final TypeVar retType, MethodTree tree, VisitorState state) {
    CharSequence source = state.getSourceForNode((JCTree) tree);
    if (source == null) {
        // No fix if we don't have end positions.
        return describeMatch(tree);
    }/*from   w w w.ja v  a2  s.  c  o m*/

    int paramIndex = -1;
    for (int idx = 0; idx < tree.getTypeParameters().size(); ++idx) {
        if (((JCTypeParameter) tree.getTypeParameters().get(idx)).type.equals(retType)) {
            paramIndex = idx;
            break;
        }
    }

    if (paramIndex == -1) {
        return Description.NO_MATCH;
    }

    SuggestedFix.Builder fix = SuggestedFix.builder();
    fix = removeTypeParam(paramIndex, tree.getTypeParameters(), state, fix);

    // Replace usages of the type parameter with its upper-bound, both inside the method body
    // and in the return type.
    // e.g. <A, B> B f(A a) { return (B) a; } -> <A> Object f(A a) { return (Object) a; }
    String qualifiedName = retType.bound != null ? retType.bound.toString() : "Object";
    // Always use simple names.
    // TODO(cushon) - this isn't always correct, but it's better than defaulting to
    // fully-qualified names. There should be a better way to do this.
    String newType = Iterables.getLast(Splitter.on('.').split(qualifiedName));

    rewriteTypeUsages(retType, tree.getBody(), newType, fix, state);
    rewriteTypeUsages(retType, tree.getReturnType(), newType, fix, state);

    return describeMatch(tree, fix.build());
}

From source file:org.splevo.jamopp.refactoring.java.ifelse.IfStaticConfigClassField.java

@Override
protected List<Resource> refactorFullyAutomated(VariationPoint variationPoint,
        Map<String, Object> refactoringOptions) {
    Map<String, List<Field>> fieldToFieldName = Maps.newHashMap();
    Map<String, List<Integer>> positionToFieldName = Maps.newHashMap();
    Map<String, List<Expression>> initialValuesToFieldName = new HashMap<String, List<Expression>>();
    Map<Expression, String> variantIDToInitialValue = new HashMap<Expression, String>();

    Class vpLocation = (Class) ((JaMoPPJavaSoftwareElement) variationPoint.getLocation()).getJamoppElement();

    fillMaps(variationPoint, fieldToFieldName, initialValuesToFieldName, variantIDToInitialValue,
            positionToFieldName);/* w ww  .  j  a va 2s  . co  m*/

    RefactoringUtil.deleteVariableMembersFromLeading(variationPoint);

    Block nonStaticBlock = StatementsFactory.eINSTANCE.createBlock();
    Block staticBlock = StatementsFactory.eINSTANCE.createBlock();
    staticBlock.getModifiers().add(ModifiersFactory.eINSTANCE.createStatic());

    for (String fieldName : fieldToFieldName.keySet()) {
        List<Field> fields = fieldToFieldName.get(fieldName);
        List<Expression> initialValues = initialValuesToFieldName.get(fieldName);
        List<Integer> fieldPositions = positionToFieldName.get(fieldName);

        Field field = Iterables.getLast(fields);
        int fieldPos = Iterables.getLast(fieldPositions);

        registerReplacement(fields, field);

        vpLocation.getMembers().add(fieldPos, field);

        if (initialValues.size() > 1) {
            RefactoringUtil.removeFinalIfApplicable(field);

            field.setInitialValue(null);

            for (Expression value : initialValues) {
                String variantId = variantIDToInitialValue.get(value);

                ExpressionStatement fieldAssignment = createFieldAssignment(field, value);

                Condition condition = this.ifElseRefactoringUtil.createVariabilityCondition(variationPoint,
                        variantId);
                Block ifBlock = (Block) condition.getStatement();
                ifBlock.getStatements().add(fieldAssignment);

                if (isStatic(field)) {
                    staticBlock.getStatements().add(condition);
                    registerVariantSpecificNewEObject(condition, variantId);
                } else {
                    nonStaticBlock.getStatements().add(condition);
                    registerVariantSpecificNewEObject(condition, variantId);
                }
            }
        }
    }
    if (staticBlock.getStatements().size() > 0) {
        vpLocation.getMembers().add(0, staticBlock);
    }
    if (nonStaticBlock.getStatements().size() > 0) {
        vpLocation.getMembers().add(0, nonStaticBlock);
    }

    ArrayList<Resource> resourceList = Lists.newArrayList(vpLocation.eResource());

    Optional<Resource> configClassResource = ifElseRefactoringUtil.createConfigurationClass(variationPoint,
            refactoringOptions);
    if (configClassResource.isPresent()) {
        resourceList.add(configClassResource.get());
    }

    return resourceList;
}

From source file:org.apache.aurora.scheduler.pruning.TaskHistoryPruner.java

/**
 * When triggered, records an inactive task state change.
 *
 * @param change Event when a task changes state.
 *//*w w w  . j av a2s.  co  m*/
@Subscribe
public void recordStateChange(TaskStateChange change) {
    if (Tasks.isTerminated(change.getNewState())) {
        long timeoutBasis = change.isTransition() ? clock.nowMillis()
                : Iterables.getLast(change.getTask().getTaskEvents()).getTimestamp();
        registerInactiveTask(Tasks.getJob(change.getTask()), change.getTaskId(),
                calculateTimeout(timeoutBasis));
    }
}

From source file:com.palantir.common.collect.IterableView.java

public T getLast() {
    return Iterables.getLast(delegate());
}

From source file:com.android.tools.idea.welcome.wizard.ConsoleHighlighter.java

@VisibleForTesting
synchronized int getOffsetRangeIndex(int startOffset) {
    if (myRanges.isEmpty() || startOffset < 0 || startOffset >= Iterables.getLast(myRanges).end) {
        return -1;
    }/*from  ww  w. ja va2s  .  c  om*/
    int end = myRanges.size();
    int i = end / 2;
    while (true) {
        HighlightRange range = myRanges.get(i);
        if (range.end > startOffset) {
            if (range.start <= startOffset) {
                return i;
            } else {
                end = i;
                i /= 2;
            }
        } else {
            i = (i + end) / 2;
        }
    }
}