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.kitesdk.examples.demo.CreateSessions.java

private <E> Dataset<E> getLatestPartition(Dataset<E> eventsDataset) {
    Dataset<E> ds = eventsDataset;
    while (ds.getDescriptor().isPartitioned()) {
        ds = Iterables.getLast(ds.getPartitions());
    }//from   w  ww.  j  av a 2s . co m
    return ds;
}

From source file:edu.buaa.satla.analysis.core.arg.ARGPath.java

public ARGState getLastState() {
    return Iterables.getLast(states);
}

From source file:org.apache.james.mailbox.inmemory.InMemoryMessageIdManager.java

@Override
public void setInMailboxes(MessageId messageId, List<MailboxId> mailboxIds, MailboxSession mailboxSession)
        throws MailboxException {
    List<MessageResult> messages = getMessages(ImmutableList.of(messageId), FetchGroupImpl.MINIMAL,
            mailboxSession);//  w ww . ja v  a 2s  .c  o  m

    filterOnMailboxSession(mailboxIds, mailboxSession);

    if (!messages.isEmpty()) {
        ImmutableSet<MailboxId> currentMailboxes = currentMailboxes(messages).toSet();

        HashSet<MailboxId> targetMailboxes = Sets.newHashSet(mailboxIds);
        List<MailboxId> mailboxesToRemove = ImmutableList
                .copyOf(Sets.difference(currentMailboxes, targetMailboxes));
        SetView<MailboxId> mailboxesToAdd = Sets.difference(targetMailboxes, currentMailboxes);

        MessageResult referenceMessage = Iterables.getLast(messages);
        for (MailboxId mailboxId : mailboxesToAdd) {
            MessageRange messageRange = referenceMessage.getUid().toRange();
            mailboxManager.copyMessages(messageRange, referenceMessage.getMailboxId(), mailboxId,
                    mailboxSession);
            mailboxManager.getMailbox(mailboxId, mailboxSession).setFlags(referenceMessage.getFlags(),
                    FlagsUpdateMode.REPLACE, messageRange, mailboxSession);
        }

        for (MessageResult message : messages) {
            delete(message.getMessageId(), mailboxesToRemove, mailboxSession);
        }
    }
}

From source file:org.jclouds.gogrid.GoGridLiveTestDisabled.java

/**
 * Tests server start, reboot and deletion. Also verifies IP services and job services.
 *///from   www.j  a v a2 s  .c o m
@Test(enabled = true)
public void testServerLifecycle() {
    int serverCountBeforeTest = api.getServerServices().getServerList().size();

    final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6);
    serversToDeleteAfterTheTests.add(nameOfServer);

    Set<Ip> availableIps = api.getIpServices().getUnassignedPublicIpList();
    Ip availableIp = Iterables.getLast(availableIps);

    String ram = Iterables.get(api.getServerServices().getRamSizes(), 0).getName();

    Server createdServer = api.getServerServices().addServer(nameOfServer,
            "GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram, availableIp.getIp());
    assertNotNull(createdServer);
    assert serverLatestJobCompleted.apply(createdServer);

    // get server by name
    Set<Server> response = api.getServerServices().getServersByName(nameOfServer);
    assert (response.size() == 1);

    // restart the server
    api.getServerServices().power(nameOfServer, PowerCommand.RESTART);

    Set<Job> jobs = api.getJobServices().getJobsForObjectName(nameOfServer);
    assert ("RestartVirtualServer".equals(Iterables.getLast(jobs).getCommand().getName()));

    assert serverLatestJobCompleted.apply(createdServer);

    int serverCountAfterAddingOneServer = api.getServerServices().getServerList().size();
    assert serverCountAfterAddingOneServer == serverCountBeforeTest
            + 1 : "There should be +1 increase in the number of servers since the test started";

    // delete the server
    api.getServerServices().deleteByName(nameOfServer);

    jobs = api.getJobServices().getJobsForObjectName(nameOfServer);
    assert ("DeleteVirtualServer".equals(Iterables.getLast(jobs).getCommand().getName()));

    assert serverLatestJobCompleted.apply(createdServer);

    int serverCountAfterDeletingTheServer = api.getServerServices().getServerList().size();
    assert serverCountAfterDeletingTheServer == serverCountBeforeTest : "There should be the same # of servers as since the test started";

    // make sure that IP is put back to "unassigned"
    assert api.getIpServices().getUnassignedIpList().contains(availableIp);
}

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

/**
 * Returns the last instruction from a code container.
 * // ww  w .  ja  va 2  s  . c  om
 * @param container The code container.
 * 
 * @return The last instruction from the code container.
 */
private static IInstruction getLastInstruction(final ICodeContainer<?> container) {
    return Iterables.getLast(container.getInstructions());
}

From source file:org.jclouds.scriptbuilder.statements.git.CloneGitRepo.java

/**
 * {@inheritDoc}/* w  ww  .  j  a v a 2  s .c  o m*/
 */
@Override
public String render(OsFamily arg0) {
    StringBuilder command = new StringBuilder();
    command.append("git clone");
    if (gitRepoAndRef.getBranch().isPresent())
        command.append(" -b ").append(gitRepoAndRef.getBranch().get());
    command.append(' ').append(gitRepoAndRef.getRepository().toASCIIString());
    if (directory.isPresent())
        command.append(' ').append(directory.get());
    command.append("{lf}");
    command.append("{cd} ").append(directory.or(Iterables
            .getLast(Splitter.on('/').split(gitRepoAndRef.getRepository().getPath())).replace(".git", "")));
    if (gitRepoAndRef.getTag().isPresent()) {
        command.append("{lf}").append("git checkout ").append(gitRepoAndRef.getTag().get());
    }
    return Statements.exec(command.toString()).render(arg0);
}

From source file:com.eucalyptus.reporting.Counter.java

private long created(final List<CountPeriod<C>> periodList) {
    return periodList.isEmpty() ? clock.millis() : Iterables.getLast(periodList).key.created;
}

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

@GET(path = "/backend/error/messages", permission = "agent:error:overview")
String getData(@BindAgentRollupId String agentRollupId, @BindRequest ErrorMessageRequest request,
        @BindAutoRefresh boolean autoRefresh) throws Exception {
    TraceQuery query = ImmutableTraceQuery.builder().transactionType(request.transactionType())
            .transactionName(request.transactionName()).from(request.from()).to(request.to()).build();
    AggregateQuery aggregateQuery = ImmutableAggregateQuery.builder().transactionType(request.transactionType())
            .transactionName(request.transactionName()).from(request.from()).to(request.to())
            .rollupLevel(/*from   w  ww . j a  v a 2 s .  c  o m*/
                    rollupLevelService.getRollupLevelForView(request.from(), request.to(), DataKind.GENERAL))
            .build();
    ErrorMessageFilter filter = ImmutableErrorMessageFilter.builder().addAllIncludes(request.include())
            .addAllExcludes(request.exclude()).build();
    long liveCaptureTime = clock.currentTimeMillis();
    List<ThroughputAggregate> throughputAggregates = transactionCommonService
            .getThroughputAggregates(agentRollupId, aggregateQuery, autoRefresh);
    if (throughputAggregates.isEmpty() && fallBackToLargestAggregates(aggregateQuery)) {
        // fall back to largest aggregates in case expiration settings have recently changed
        aggregateQuery = withLargestRollupLevel(aggregateQuery);
        throughputAggregates = transactionCommonService.getThroughputAggregates(agentRollupId, aggregateQuery,
                autoRefresh);
        if (!throughputAggregates.isEmpty()
                && ignoreFallBackData(aggregateQuery, Iterables.getLast(throughputAggregates).captureTime())) {
            // this is probably data from before the requested time period
            throughputAggregates = ImmutableList.of();
        }
    }
    long dataPointIntervalMillis = configRepository.getRollupConfigs().get(aggregateQuery.rollupLevel())
            .intervalMillis();
    DataSeries dataSeries = new DataSeries(null);
    Map<Long, Long[]> dataSeriesExtra = Maps.newHashMap();
    Map<Long, Long> transactionCountMap = Maps.newHashMap();
    for (ThroughputAggregate unfilteredErrorPoint : throughputAggregates) {
        transactionCountMap.put(unfilteredErrorPoint.captureTime(), unfilteredErrorPoint.transactionCount());
    }
    List<ErrorMessageCount> records = Lists.newArrayList();
    boolean moreAvailable = false;
    if (!throughputAggregates.isEmpty()) {
        long maxCaptureTime = Iterables.getLast(throughputAggregates).captureTime();
        ErrorMessageResult result = traceRepository.readErrorMessages(agentRollupId,
                ImmutableTraceQuery.builder().copyFrom(query).to(maxCaptureTime).build(), filter,
                dataPointIntervalMillis, request.errorMessageLimit());
        List<ErrorPoint> errorPoints = Lists.newArrayList();
        for (ErrorMessagePoint traceErrorPoint : result.points()) {
            long captureTime = traceErrorPoint.captureTime();
            if (captureTime > maxCaptureTime) {
                // traceRepository.readErrorMessages() returns capture time on resolutionMillis,
                // while throughputAggregates may return last capture time at a finer rollup
                // level
                captureTime = maxCaptureTime;
            }
            Long transactionCount = transactionCountMap.get(captureTime);
            if (transactionCount != null) {
                errorPoints.add(
                        ImmutableErrorPoint.of(captureTime, traceErrorPoint.errorCount(), transactionCount));
            }
        }
        populateDataSeries(query, errorPoints, dataSeries, dataSeriesExtra, dataPointIntervalMillis,
                liveCaptureTime);
        records = result.counts().records();
        moreAvailable = result.counts().moreAvailable();
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeObjectField("dataSeries", dataSeries);
        jg.writeNumberField("dataPointIntervalMillis", dataPointIntervalMillis);
        jg.writeObjectField("dataSeriesExtra", dataSeriesExtra);
        jg.writeObjectField("errorMessages", records);
        jg.writeBooleanField("moreErrorMessagesAvailable", moreAvailable);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

From source file:org.sonar.php.checks.formatting.IndentationCheck.java

private void checkImplementListIndentation(ClassDeclarationTree classTree) {
    if (check.isInterfacesIndentation && classTree.is(Tree.Kind.CLASS_DECLARATION)
            && !classTree.superInterfaces().isEmpty()) {

        List<Tree> interfaceList = ImmutableList.<Tree>copyOf(classTree.superInterfaces());
        SyntaxToken classToken = classTree.classEntryTypeToken();
        SyntaxToken lastInterfaceToken = ((PHPTree) Iterables.getLast(classTree.superInterfaces()))
                .getFirstToken();//from   ww w  .  j av  a 2 s .co m
        int expectedColumn = classToken.column() + PSR2_INDENTATION;

        if (!TokenUtils.isOnSameLine(classToken, lastInterfaceToken)) {

            if (!isCorrectlySplitOnLines(classToken.line(), interfaceList)) {
                check.reportIssue(String.format(INTERFACE_SPLIT_MESSAGE, classToken.line()),
                        classTree.superInterfaces().get(0));

            } else if (!isCorrectlyIndented(expectedColumn, interfaceList)) {
                check.reportIssue(String.format(INTERFACE_INDENTATION, expectedColumn),
                        classTree.superInterfaces().get(0));
            }
        }
    }
}

From source file:org.jpmml.converter.mining.MiningModelUtil.java

static public MiningModel createModelChain(FieldName targetField, List<FieldName> activeFields,
        List<? extends Model> models) {
    Segmentation segmentation = createSegmentation(Segmentation.MultipleModelMethod.MODEL_CHAIN, models);

    Model lastModel = Iterables.getLast(models);

    MiningSchema miningSchema = ModelUtil.createMiningSchema(targetField, activeFields);

    MiningModel miningModel = new MiningModel(lastModel.getMiningFunction(), miningSchema)
            .setSegmentation(segmentation);

    return miningModel;
}