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.graylog.plugins.pipelineprocessor.processors.PipelineInterpreter.java

private boolean executeRuleActions(Rule rule, Message message, String msgId, Pipeline pipeline,
        EvaluationContext context, InterpreterListener interpreterListener) {
    rule.markExecution();/*  ww  w .  j a  va2s .  c  o m*/
    interpreterListener.executeRule(rule, pipeline);
    log.debug("[{}] rule `{}` matched running actions", msgId, rule.name());
    final GeneratedRule generatedRule = rule.generatedRule();
    if (generatedRule != null) {
        try {
            generatedRule.then(context);
            return true;
        } catch (Exception ignored) {
            final EvaluationContext.EvalError lastError = Iterables.getLast(context.evaluationErrors());
            appendProcessingError(rule, message, lastError.toString());
            log.debug("Encountered evaluation error, skipping rest of the rule: {}", lastError);
            rule.markFailure();
            return false;
        }
    } else {
        if (ConfigurationStateUpdater.isAllowCodeGeneration()) {
            throw new IllegalStateException("Should have generated code and not interpreted the tree");
        }
        for (Statement statement : rule.then()) {
            if (!evaluateStatement(message, interpreterListener, pipeline, context, rule, statement)) {
                // statement raised an error, skip the rest of the rule
                return false;
            }
        }
    }
    return true;
}

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

private VariableTrackingPrecision joinSubtreePrecisions(final ReachedSet pReached,
        Collection<ARGState> targetsReachableFromRoot) {

    VariableTrackingPrecision precision = extractPrecision(pReached,
            Iterables.getLast(targetsReachableFromRoot));
    // join precisions of all target states
    for (ARGState target : targetsReachableFromRoot) {
        VariableTrackingPrecision precisionOfTarget = extractPrecision(pReached, target);
        precision = precision.join(precisionOfTarget);
    }/*ww w.  ja  va  2 s .c  o m*/

    return precision;
}

From source file:main.Tableau.java

public String notation(Entry entry) {
    List<String> result = new ArrayList<String>();
    Tableau note = new Tableau();

    // dclone tableau
    for (int c = 0; c < MAXCOLS; c++)
        for (int r = 0; r < MAXROWS; r++)
            note.tableau[c][r] = this.tableau[c][r];

    // standard notation
    String stdSrc = new String();
    String stdDst = new String();

    // descriptive notation
    List<String> dscSrc = new ArrayList<String>();
    String dscDst = new String();

    // autoplay notation
    Map<Integer, ArrayList<String>> autoPlay = new HashMap<Integer, ArrayList<String>>();
    List<String> autoSrc = new ArrayList<String>();

    boolean first = true;
    for (Move move : entry.value.node) {
        if (first) {
            first = false;//from   w w  w  . ja va2 s.c  o m
            stdSrc = move.srcRow > 0 ? Integer.toString(move.srcCol + 1) : ABCD.get(move.srcCol);

            stdDst = move.dstRow > 0 ? Integer.toString(move.dstCol + 1)
                    : move.dstCol < HOMEOFFSET ? ABCD.get(move.dstCol) : "h";

            dscDst = move.dstRow == 1 ? "e"
                    : stdDst.matches("\\d") ? note.toCard(move.dstCol, move.dstRow - 1)
                            : stdDst.equals("h") ? "h" : "f";
        }

        int homeSuit = suit(note.tableau[move.srcCol][move.srcRow]);
        if (move.origin.startsWith("a")) { // autoplay to home
            if (autoPlay.containsKey(homeSuit)) {
                autoPlay.get(homeSuit).add(note.toCard(move.srcCol, move.srcRow));
            } else {
                ArrayList<String> cardArray = new ArrayList<String>();
                cardArray.add(note.toCard(move.srcCol, move.srcRow));
                autoPlay.put(homeSuit, cardArray);
            }
        } else {
            dscSrc.add(note.toCard(move.srcCol, move.srcRow));
        }
        note.play(move);
    }
    for (Map.Entry<Integer, ArrayList<String>> suitArray : autoPlay.entrySet()) {
        ArrayList<String> cardArray = suitArray.getValue();
        autoSrc.add(cardArray.get(0) + (cardArray.size() > 1 ? "-" + Iterables.getLast(cardArray) : ""));
    }

    result.add(Integer.toString(entry.value.depth));
    result.add(stdSrc + stdDst);
    result.add(dscSrc.get(0) + (dscSrc.size() > 1 ? "-" + Iterables.getLast(dscSrc) : ""));
    result.add(dscDst);
    result.add(autoSrc.size() > 0 ? Joiner.on(';').join(autoSrc.toArray()) : "");

    return Joiner.on('|').join(result.toArray());
}

From source file:org.dcache.srm.request.Job.java

@Nonnull
public JobHistory getLastJobChange() {
    rlock();
    try {
        return Iterables.getLast(jobHistory);
    } finally {
        runlock();
    }
}

From source file:org.glowroot.ui.ReportJsonService.java

private DataSeries getDataSeriesForAverage(String agentRollupId, AggregateQuery query,
        RollupCaptureTimeFn rollupCaptureTimeFn, ROLLUP rollup, TimeZone timeZone, double gapMillis)
        throws Exception {

    DataSeries dataSeries = new DataSeries(agentDisplayRepository.readFullDisplay(agentRollupId));
    List<OverviewAggregate> aggregates = aggregateRepository.readOverviewAggregates(agentRollupId, query);
    aggregates = TransactionCommonService.rollUpOverviewAggregates(aggregates, rollupCaptureTimeFn);
    if (aggregates.isEmpty()) {
        return dataSeries;
    }//w  w  w  .ja  v a  2s  . c o  m
    OverviewAggregate lastAggregate = Iterables.getLast(aggregates);
    long lastCaptureTime = lastAggregate.captureTime();
    long lastRollupCaptureTime = rollupCaptureTimeFn.apply(lastCaptureTime);
    if (lastCaptureTime != lastRollupCaptureTime) {
        aggregates.set(aggregates.size() - 1, ImmutableOverviewAggregate.builder().copyFrom(lastAggregate)
                .captureTime(lastRollupCaptureTime).build());
    }
    OverviewAggregate priorAggregate = null;
    for (OverviewAggregate aggregate : aggregates) {
        if (priorAggregate != null && aggregate.captureTime() - priorAggregate.captureTime() > gapMillis) {
            dataSeries.addNull();
        }
        dataSeries.add(getIntervalAverage(rollup, timeZone, aggregate.captureTime()),
                aggregate.totalDurationNanos() / (aggregate.transactionCount() * NANOSECONDS_PER_MILLISECOND));
        priorAggregate = aggregate;
    }
    double totalDurationNanos = 0;
    long transactionCount = 0;
    for (OverviewAggregate aggregate : aggregates) {
        totalDurationNanos += aggregate.totalDurationNanos();
        transactionCount += aggregate.transactionCount();
    }
    // individual aggregate transaction counts cannot be zero, and aggregates is non-empty
    // (see above conditional), so transactionCount is guaranteed non-zero
    checkState(transactionCount != 0);
    dataSeries.setOverall(totalDurationNanos / (transactionCount * NANOSECONDS_PER_MILLISECOND));
    return dataSeries;
}

From source file:io.prestosql.sql.planner.RelationPlanner.java

@Override
protected RelationPlan visitJoin(Join node, Void context) {
    // TODO: translate the RIGHT join into a mirrored LEFT join when we refactor (@martint)
    RelationPlan leftPlan = process(node.getLeft(), context);

    Optional<Unnest> unnest = getUnnest(node.getRight());
    if (unnest.isPresent()) {
        if (node.getType() != Join.Type.CROSS && node.getType() != Join.Type.IMPLICIT) {
            throw notSupportedException(unnest.get(), "UNNEST on other than the right side of CROSS JOIN");
        }//w w w.  j  a  v a2 s. com
        return planCrossJoinUnnest(leftPlan, node, unnest.get());
    }

    Optional<Lateral> lateral = getLateral(node.getRight());
    if (lateral.isPresent()) {
        if (node.getType() != Join.Type.CROSS && node.getType() != Join.Type.IMPLICIT) {
            throw notSupportedException(lateral.get(), "LATERAL on other than the right side of CROSS JOIN");
        }
        return planLateralJoin(node, leftPlan, lateral.get());
    }

    RelationPlan rightPlan = process(node.getRight(), context);

    if (node.getCriteria().isPresent() && node.getCriteria().get() instanceof JoinUsing) {
        return planJoinUsing(node, leftPlan, rightPlan);
    }

    PlanBuilder leftPlanBuilder = initializePlanBuilder(leftPlan);
    PlanBuilder rightPlanBuilder = initializePlanBuilder(rightPlan);

    // NOTE: symbols must be in the same order as the outputDescriptor
    List<Symbol> outputSymbols = ImmutableList.<Symbol>builder().addAll(leftPlan.getFieldMappings())
            .addAll(rightPlan.getFieldMappings()).build();

    ImmutableList.Builder<JoinNode.EquiJoinClause> equiClauses = ImmutableList.builder();
    List<Expression> complexJoinExpressions = new ArrayList<>();
    List<Expression> postInnerJoinConditions = new ArrayList<>();

    if (node.getType() != Join.Type.CROSS && node.getType() != Join.Type.IMPLICIT) {
        Expression criteria = analysis.getJoinCriteria(node);

        RelationType left = analysis.getOutputDescriptor(node.getLeft());
        RelationType right = analysis.getOutputDescriptor(node.getRight());

        List<Expression> leftComparisonExpressions = new ArrayList<>();
        List<Expression> rightComparisonExpressions = new ArrayList<>();
        List<ComparisonExpression.Operator> joinConditionComparisonOperators = new ArrayList<>();

        for (Expression conjunct : ExpressionUtils.extractConjuncts(criteria)) {
            conjunct = ExpressionUtils.normalize(conjunct);

            if (!isEqualComparisonExpression(conjunct) && node.getType() != INNER) {
                complexJoinExpressions.add(conjunct);
                continue;
            }

            Set<QualifiedName> dependencies = SymbolsExtractor.extractNames(conjunct,
                    analysis.getColumnReferences());

            if (dependencies.stream().allMatch(left::canResolve)
                    || dependencies.stream().allMatch(right::canResolve)) {
                // If the conjunct can be evaluated entirely with the inputs on either side of the join, add
                // it to the list complex expressions and let the optimizers figure out how to push it down later.
                complexJoinExpressions.add(conjunct);
            } else if (conjunct instanceof ComparisonExpression) {
                Expression firstExpression = ((ComparisonExpression) conjunct).getLeft();
                Expression secondExpression = ((ComparisonExpression) conjunct).getRight();
                ComparisonExpression.Operator comparisonOperator = ((ComparisonExpression) conjunct)
                        .getOperator();
                Set<QualifiedName> firstDependencies = SymbolsExtractor.extractNames(firstExpression,
                        analysis.getColumnReferences());
                Set<QualifiedName> secondDependencies = SymbolsExtractor.extractNames(secondExpression,
                        analysis.getColumnReferences());

                if (firstDependencies.stream().allMatch(left::canResolve)
                        && secondDependencies.stream().allMatch(right::canResolve)) {
                    leftComparisonExpressions.add(firstExpression);
                    rightComparisonExpressions.add(secondExpression);
                    joinConditionComparisonOperators.add(comparisonOperator);
                } else if (firstDependencies.stream().allMatch(right::canResolve)
                        && secondDependencies.stream().allMatch(left::canResolve)) {
                    leftComparisonExpressions.add(secondExpression);
                    rightComparisonExpressions.add(firstExpression);
                    joinConditionComparisonOperators.add(comparisonOperator.flip());
                } else {
                    // the case when we mix symbols from both left and right join side on either side of condition.
                    complexJoinExpressions.add(conjunct);
                }
            } else {
                complexJoinExpressions.add(conjunct);
            }
        }

        leftPlanBuilder = subqueryPlanner.handleSubqueries(leftPlanBuilder, leftComparisonExpressions, node);
        rightPlanBuilder = subqueryPlanner.handleSubqueries(rightPlanBuilder, rightComparisonExpressions, node);

        // Add projections for join criteria
        leftPlanBuilder = leftPlanBuilder.appendProjections(leftComparisonExpressions, symbolAllocator,
                idAllocator);
        rightPlanBuilder = rightPlanBuilder.appendProjections(rightComparisonExpressions, symbolAllocator,
                idAllocator);

        for (int i = 0; i < leftComparisonExpressions.size(); i++) {
            if (joinConditionComparisonOperators.get(i) == ComparisonExpression.Operator.EQUAL) {
                Symbol leftSymbol = leftPlanBuilder.translate(leftComparisonExpressions.get(i));
                Symbol rightSymbol = rightPlanBuilder.translate(rightComparisonExpressions.get(i));

                equiClauses.add(new JoinNode.EquiJoinClause(leftSymbol, rightSymbol));
            } else {
                Expression leftExpression = leftPlanBuilder.rewrite(leftComparisonExpressions.get(i));
                Expression rightExpression = rightPlanBuilder.rewrite(rightComparisonExpressions.get(i));
                postInnerJoinConditions.add(new ComparisonExpression(joinConditionComparisonOperators.get(i),
                        leftExpression, rightExpression));
            }
        }
    }

    PlanNode root = new JoinNode(idAllocator.getNextId(), JoinNode.Type.typeConvert(node.getType()),
            leftPlanBuilder.getRoot(), rightPlanBuilder.getRoot(), equiClauses.build(),
            ImmutableList.<Symbol>builder().addAll(leftPlanBuilder.getRoot().getOutputSymbols())
                    .addAll(rightPlanBuilder.getRoot().getOutputSymbols()).build(),
            Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());

    if (node.getType() != INNER) {
        for (Expression complexExpression : complexJoinExpressions) {
            Set<InPredicate> inPredicates = subqueryPlanner.collectInPredicateSubqueries(complexExpression,
                    node);
            if (!inPredicates.isEmpty()) {
                InPredicate inPredicate = Iterables.getLast(inPredicates);
                throw notSupportedException(inPredicate, "IN with subquery predicate in join condition");
            }
        }

        // subqueries can be applied only to one side of join - left side is selected in arbitrary way
        leftPlanBuilder = subqueryPlanner.handleUncorrelatedSubqueries(leftPlanBuilder, complexJoinExpressions,
                node);
    }

    RelationPlan intermediateRootRelationPlan = new RelationPlan(root, analysis.getScope(node), outputSymbols);
    TranslationMap translationMap = new TranslationMap(intermediateRootRelationPlan, analysis,
            lambdaDeclarationToSymbolMap);
    translationMap.setFieldMappings(outputSymbols);
    translationMap.putExpressionMappingsFrom(leftPlanBuilder.getTranslations());
    translationMap.putExpressionMappingsFrom(rightPlanBuilder.getTranslations());

    if (node.getType() != INNER && !complexJoinExpressions.isEmpty()) {
        Expression joinedFilterCondition = ExpressionUtils.and(complexJoinExpressions);
        Expression rewrittenFilterCondition = translationMap.rewrite(joinedFilterCondition);
        root = new JoinNode(idAllocator.getNextId(), JoinNode.Type.typeConvert(node.getType()),
                leftPlanBuilder.getRoot(), rightPlanBuilder.getRoot(), equiClauses.build(),
                ImmutableList.<Symbol>builder().addAll(leftPlanBuilder.getRoot().getOutputSymbols())
                        .addAll(rightPlanBuilder.getRoot().getOutputSymbols()).build(),
                Optional.of(rewrittenFilterCondition), Optional.empty(), Optional.empty(), Optional.empty());
    }

    if (node.getType() == INNER) {
        // rewrite all the other conditions using output symbols from left + right plan node.
        PlanBuilder rootPlanBuilder = new PlanBuilder(translationMap, root, analysis.getParameters());
        rootPlanBuilder = subqueryPlanner.handleSubqueries(rootPlanBuilder, complexJoinExpressions, node);

        for (Expression expression : complexJoinExpressions) {
            postInnerJoinConditions.add(rootPlanBuilder.rewrite(expression));
        }
        root = rootPlanBuilder.getRoot();

        Expression postInnerJoinCriteria;
        if (!postInnerJoinConditions.isEmpty()) {
            postInnerJoinCriteria = ExpressionUtils.and(postInnerJoinConditions);
            root = new FilterNode(idAllocator.getNextId(), root, postInnerJoinCriteria);
        }
    }

    return new RelationPlan(root, analysis.getScope(node), outputSymbols);
}