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.glowroot.ui.TransactionCommonService.java

List<OverviewAggregate> getOverviewAggregates(String agentRollupId, AggregateQuery query, boolean autoRefresh)
        throws Exception {
    LiveResult<OverviewAggregate> liveResult;
    long revisedTo;
    if (autoRefresh) {
        liveResult = null;// w w w  . jav a 2  s  .c  o m
        revisedTo = query.to();
    } else {
        liveResult = liveAggregateRepository.getOverviewAggregates(agentRollupId, query);
        revisedTo = liveResult == null ? query.to() : liveResult.revisedTo();
    }
    AggregateQuery revisedQuery = ImmutableAggregateQuery.builder().copyFrom(query).to(revisedTo).build();
    List<OverviewAggregate> aggregates = aggregateRepository.readOverviewAggregates(agentRollupId,
            revisedQuery);
    if (revisedQuery.rollupLevel() == 0) {
        if (liveResult != null) {
            aggregates = Lists.newArrayList(aggregates);
            aggregates.addAll(liveResult.get());
        }
        return aggregates;
    }
    long nonRolledUpFrom = revisedQuery.from();
    if (!aggregates.isEmpty()) {
        nonRolledUpFrom = Iterables.getLast(aggregates).captureTime() + 1;
    }
    List<OverviewAggregate> orderedNonRolledUpAggregates = Lists.newArrayList();
    if (nonRolledUpFrom <= revisedTo) {
        orderedNonRolledUpAggregates
                .addAll(aggregateRepository.readOverviewAggregates(agentRollupId, ImmutableAggregateQuery
                        .builder().copyFrom(revisedQuery).from(nonRolledUpFrom).rollupLevel(0).build()));
    }
    if (liveResult != null) {
        orderedNonRolledUpAggregates.addAll(liveResult.get());
    }
    aggregates = Lists.newArrayList(aggregates);
    long fixedIntervalMillis = configRepository.getRollupConfigs().get(revisedQuery.rollupLevel())
            .intervalMillis();
    aggregates.addAll(rollUpOverviewAggregates(orderedNonRolledUpAggregates,
            new RollupCaptureTimeFn(fixedIntervalMillis)));
    if (aggregates.size() >= 2) {
        long currentTime = clock.currentTimeMillis();
        OverviewAggregate nextToLastAggregate = aggregates.get(aggregates.size() - 2);
        if (currentTime - nextToLastAggregate.captureTime() < 60000) {
            aggregates.remove(aggregates.size() - 1);
        }
    }
    return aggregates;
}

From source file:gov.nih.nci.firebird.test.data.AbstractDataComponentBuilder.java

Organization getSponsorWithProtocolRegistrationsOrganization() {
    String sponsorExternalId = Iterables
            .getLast(gridResources.getSponsorWithProtocolRegistrationsExternalIds());
    return retrieveSponsorOrganization(sponsorExternalId);
}

From source file:org.opendaylight.openflowplugin.applications.lldpspeaker.NodeConnectorInventoryEventTranslator.java

/**
 * @param key/*from   w  w  w . j  a va2 s .c  o  m*/
 * @param iiToFlowCapableNodeConnector
 * @return
 */
private boolean compareIITail(InstanceIdentifier<?> ii1, InstanceIdentifier<?> ii2) {
    return Iterables.getLast(ii1.getPathArguments()).equals(Iterables.getLast(ii2.getPathArguments()));
}

From source file:org.jboss.hal.ballroom.wizard.Wizard.java

private Wizard(Builder<C, S> builder) {
    this.context = builder.context;
    this.steps = new LinkedHashMap<>(builder.steps);
    this.steps.values().forEach(step -> step.init(this));
    this.stepElements = new LinkedHashMap<>();
    this.stepIndicators = new HashMap<>();
    this.initialState = builder.initialState == null ? steps.keySet().iterator().next() : builder.initialState;
    this.back = builder.back;
    this.next = builder.next;
    this.lastStates = builder.lastStates == null ? EnumSet.of(Iterables.getLast(steps.keySet()))
            : builder.lastStates;//from   w w w.j  a  va  2 s  . com
    this.finishCallback = builder.finishCallback;
    this.cancelCallback = builder.cancelCallback;
    this.showsError = false;
    this.stayOpenAfterFinish = builder.stayOpenAfterFinish;
    this.finishCanClose = false;

    reset();
    Wizard.titleElement.textContent = builder.title;
    handlerRegistration = HandlerRegistrations.compose(bind(closeIcon, click, event -> onCancel()),
            bind(cancelButton, click, event -> onCancel()), bind(backButton, click, event -> onBack()),
            bind(nextButton, click, event -> onNext()));
}

From source file:com.palantir.atlasdb.sweep.SweepTaskRunner.java

public SweepResults run(String tableName, @Nullable byte[] startRow) {
    Preconditions.checkNotNull(tableName);
    Preconditions.checkState(!tableName.startsWith(AtlasDbConstants.NAMESPACE_PREFIX),
            "The sweeper should not be run on tables passed through namespace mapping.");
    Preconditions.checkState(!AtlasDbConstants.hiddenTables.contains(tableName));

    // Earliest start timestamp of any currently open transaction, with two caveats:
    // (1) unreadableTimestamps are calculated via wall-clock time, and so may not be correct
    //     under pathological clock conditions
    // (2) immutableTimestamps do not account for locks have timed out after checking their locks;
    //     such a transaction may have a start timestamp less than the immutableTimestamp, and it
    //     could still get successfully committed (its commit timestamp may or may not be less than
    //     the immutableTimestamp
    // Note that this is fine, because we'll either
    // (1) force old readers to abort (if they read a garbage collection sentinel), or
    // (2) force old writers to retry (note that we must roll back any uncommitted transactions that
    //     we encounter
    SweepStrategy sweepStrategy = sweepStrategyManager.get().get(tableName);
    if (sweepStrategy == null) {
        sweepStrategy = SweepStrategy.CONSERVATIVE;
    } else if (sweepStrategy == SweepStrategy.NOTHING) {
        return new SweepResults(null, 0, 0);
    }/* w ww.j  a v a  2 s .c om*/
    if (startRow == null) {
        startRow = new byte[0];
    }
    int batchSize = batchSizeSupplier.get();
    RangeRequest rangeRequest = RangeRequest.builder().startRowInclusive(startRow).batchHint(batchSize).build();

    long sweepTimestamp = getSweepTimestamp(tableName);
    ClosableIterator<RowResult<Value>> valueResults;
    if (sweepStrategy == SweepStrategy.CONSERVATIVE) {
        valueResults = ClosableIterators.wrap(ImmutableList.<RowResult<Value>>of().iterator());
    } else {
        valueResults = keyValueService.getRange(tableName, rangeRequest, sweepTimestamp);
    }

    ClosableIterator<RowResult<Set<Long>>> rowResults = keyValueService.getRangeOfTimestamps(tableName,
            rangeRequest, sweepTimestamp);

    try {
        List<RowResult<Set<Long>>> rowResultTimestamps = ImmutableList
                .copyOf(Iterators.limit(rowResults, batchSize));
        PeekingIterator<RowResult<Value>> peekingValues = Iterators.peekingIterator(valueResults);
        Set<Cell> sentinelsToAdd = Sets.newHashSet();
        Multimap<Cell, Long> rowTimestamps = getTimestampsFromRowResults(rowResultTimestamps, sweepStrategy);
        Multimap<Cell, Long> cellTsPairsToSweep = getCellTsPairsToSweep(rowTimestamps, peekingValues,
                sweepTimestamp, sweepStrategy, sentinelsToAdd);
        sweepCells(tableName, cellTsPairsToSweep, sentinelsToAdd);
        byte[] nextRow = rowResultTimestamps.size() < batchSize ? null
                : RangeRequests.getNextStartRow(false, Iterables.getLast(rowResultTimestamps).getRowName());
        return new SweepResults(nextRow, rowResultTimestamps.size(), cellTsPairsToSweep.size());
    } finally {
        rowResults.close();
        valueResults.close();
    }
}

From source file:eu.trentorise.opendata.semtext.SemTexts.java

/**
 *
 * Checks spans are all be valid spans (see {@link SemTexts#checkSpan(int, int, Object)
 * }/*ww w  .  j av a  2 s .  c  o  m*/
 * and are non-overlapping (a span end offset may coincide with next span
 * start offset). Spans must be contained within {@code leftOffset} and
 * {@code rightOffset} (last span end offset may coincide with
 * {@code rightOffset}).
 *
 * @param prependedErrorMessage the exception message to use if the check
 * fails; will be converted to a string using String.valueOf(Object) and
 * prepended to more specific error messages.
 *
 * @throws IllegalArgumentException on invalid spans
 */
public static void checkSpans(Iterable<? extends Span> spans, int leftOffset, int rightOffset,
        @Nullable Object prependedErrorMessage) {

    checkArgument(spans != null, "%s -- spans are null!", prependedErrorMessage);
    checkSpan(leftOffset, rightOffset, prependedErrorMessage);

    // check containment        
    if (!Iterables.isEmpty(spans)) {
        int lowerBound = Iterables.getFirst(spans, null).getStart();
        int upperBound = Iterables.getLast(spans).getEnd();
        if (lowerBound < leftOffset || upperBound > rightOffset) {
            throw new IllegalArgumentException(String.valueOf(prependedErrorMessage)
                    + " -- Reason: Provided spans exceed container span! Expected: [" + leftOffset + ","
                    + rightOffset + "] - Found: [" + lowerBound + "," + upperBound + "]");
        }
    }

    // check overlaps
    @Nullable
    Span lastSpan = null;
    for (Span span : spans) {
        checkSpan(span.getStart(), span.getEnd(), prependedErrorMessage);
        if (lastSpan != null && lastSpan.getEnd() > span.getStart()) {
            throw new IllegalArgumentException(String.valueOf(prependedErrorMessage)
                    + " -- Found overlapping span! Span " + lastSpan + " overlaps with span " + span);
        }
        lastSpan = span;
    }

}

From source file:com.google.security.zynamics.binnavi.ZyGraph.Implementations.CNodeFunctions.java

/**
 * Splits a node.//from w  w w. j ava2s .co  m
 * 
 * @param view View the node belongs to.
 * @param originalNode Node to split.
 * @param instruction Instruction after which the node is split.
 */
public static void splitAfter(final INaviView view, final INaviCodeNode originalNode,
        final INaviInstruction instruction) {
    final Iterable<INaviInstruction> oldInstructions = originalNode.getInstructions();

    if (instruction == Iterables.getLast(oldInstructions)) {
        // Splitting after the last instruction of a node does not make
        // sense at all.

        return;
    }

    // Step I: Find out what instructions belong to the new upper block and what
    // instructions belong to the new lower block.

    final List<INaviInstruction> upperInstructions = new ArrayList<INaviInstruction>();
    final List<INaviInstruction> lowerInstructions = new ArrayList<INaviInstruction>();

    List<INaviInstruction> currentInstructions = upperInstructions;

    for (final INaviInstruction oldInstruction : oldInstructions) {
        currentInstructions.add(oldInstruction);

        if (oldInstruction == instruction) {
            currentInstructions = lowerInstructions;
        }
    }

    // Step II: Create the two new code nodes.

    INaviFunction parentFunction = null;

    try {
        parentFunction = originalNode.getParentFunction();
    } catch (final MaybeNullException e) {
        // No parent function
    }

    final INaviCodeNode newNode1 = view.getContent().createCodeNode(parentFunction, upperInstructions);
    final INaviCodeNode newNode2 = view.getContent().createCodeNode(parentFunction, lowerInstructions);

    newNode1.setColor(originalNode.getColor());
    newNode1.setBorderColor(originalNode.getBorderColor());
    newNode2.setColor(originalNode.getColor());

    // Step III: Transfer node comments and instruction comments from the old node
    // to the new nodes.

    transferLocalCodeNodeComments(originalNode, newNode1, newNode2);

    // Step IV: Connect the two new nodes.

    view.getContent().createEdge(newNode1, newNode2, EdgeType.JUMP_UNCONDITIONAL);

    // Step V: Recreate the incoming and outgoing edges of the old node.

    for (final INaviEdge incomingEdge : originalNode.getIncomingEdges()) {
        view.getContent().createEdge(incomingEdge.getSource(), newNode1, incomingEdge.getType());
    }

    for (final INaviEdge outgoingEdge : originalNode.getOutgoingEdges()) {
        view.getContent().createEdge(newNode2, outgoingEdge.getTarget(), outgoingEdge.getType());
    }

    // Step VI: Get rid of the old node.

    view.getContent().deleteNode(originalNode);
}

From source file:org.onos.yangtools.binding.generator.util.Types.java

public static @Nullable String getOuterClassName(final Type valueType) {
    final String pkgName = valueType.getPackageName();
    if (CharMatcher.JAVA_UPPER_CASE.indexIn(pkgName) >= 0) {
        // It is inner class.
        return Iterables.getLast(DOT_SPLITTER.split(pkgName));
    }/*from w w w .j  av  a 2s.com*/
    return null;
}

From source file:io.opencensus.implcore.stats.StatsTestUtil.java

@Nullable
private static List<Long> removeTrailingZeros(List<Long> longs) {
    if (longs == null) {
        return null;
    }/*w w  w. jav a  2  s .  c o m*/
    List<Long> truncated = new ArrayList<Long>(longs);
    while (!truncated.isEmpty() && Iterables.getLast(truncated) == 0) {
        truncated.remove(truncated.size() - 1);
    }
    return truncated;
}

From source file:com.github.benmanes.caffeine.cache.LocalCacheFactoryGenerator.java

private void addLocalCacheSpec(String className, boolean isFinal, Set<Feature> features) {
    TypeName superClass;/*from www . jav a  2  s  .  c o  m*/
    Set<Feature> parentFeatures;
    Set<Feature> generateFeatures;
    if (features.size() == 2) {
        parentFeatures = ImmutableSet.of();
        generateFeatures = features;
        superClass = BOUNDED_LOCAL_CACHE;
    } else {
        parentFeatures = ImmutableSet.copyOf(Iterables.limit(features, features.size() - 1));
        generateFeatures = ImmutableSet.of(Iterables.getLast(features));
        superClass = ParameterizedTypeName
                .get(ClassName.bestGuess(encode(Feature.makeClassName(parentFeatures))), kTypeVar, vTypeVar);
    }

    LocalCacheContext context = new LocalCacheContext(superClass, className, isFinal, parentFeatures,
            generateFeatures);
    for (LocalCacheRule rule : rules) {
        rule.accept(context);
    }
    factory.addType(context.cache.build());
}