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.robotframework.ide.eclipse.main.plugin.debug.model.RobotDebugTarget.java

public KeywordContext getLastKeywordFromCurrentContext() {
    if (currentKeywordsDebugContextMap.size() > 0) {
        return Iterables.getLast(currentKeywordsDebugContextMap.values());
    }/*from  w ww.  j ava 2  s  . com*/
    return new KeywordContext();
}

From source file:com.google.gerrit.server.git.MergeSuperSet.java

private ChangeSet completeChangeSetWithoutTopic(ReviewDb db, ChangeSet changes, CurrentUser user)
        throws IOException, OrmException {
    Collection<ChangeData> visibleChanges = new ArrayList<>();
    Collection<ChangeData> nonVisibleChanges = new ArrayList<>();

    // For each target branch we run a separate rev walk to find open changes
    // reachable from changes already in the merge super set.
    ImmutableListMultimap<Branch.NameKey, ChangeData> bc = byBranch(
            Iterables.concat(changes.changes(), changes.nonVisibleChanges()));
    for (Branch.NameKey b : bc.keySet()) {
        OpenRepo or = getRepo(b.getParentKey());
        List<RevCommit> visibleCommits = new ArrayList<>();
        List<RevCommit> nonVisibleCommits = new ArrayList<>();
        for (ChangeData cd : bc.get(b)) {
            checkState(cd.hasChangeControl(), "completeChangeSet forgot to set changeControl for current user"
                    + " at ChangeData creation time");

            boolean visible = changes.ids().contains(cd.getId());
            if (visible && !cd.changeControl().isVisible(db, cd)) {
                // We thought the change was visible, but it isn't.
                // This can happen if the ACL changes during the
                // completeChangeSet computation, for example.
                visible = false;/*from   w  w  w .j  av  a2  s  . c o  m*/
            }
            Collection<RevCommit> toWalk = visible ? visibleCommits : nonVisibleCommits;

            // Pick a revision to use for traversal.  If any of the patch sets
            // is visible, we use the most recent one.  Otherwise, use the current
            // patch set.
            PatchSet ps = cd.currentPatchSet();
            boolean visiblePatchSet = visible;
            if (!cd.changeControl().isPatchVisible(ps, cd)) {
                Iterable<PatchSet> visiblePatchSets = cd.visiblePatchSets();
                if (Iterables.isEmpty(visiblePatchSets)) {
                    visiblePatchSet = false;
                } else {
                    ps = Iterables.getLast(visiblePatchSets);
                }
            }

            if (submitType(cd, ps, visiblePatchSet) == SubmitType.CHERRY_PICK) {
                if (visible) {
                    visibleChanges.add(cd);
                } else {
                    nonVisibleChanges.add(cd);
                }

                continue;
            }

            // Get the underlying git commit object
            String objIdStr = ps.getRevision().get();
            RevCommit commit = or.rw.parseCommit(ObjectId.fromString(objIdStr));

            // Always include the input, even if merged. This allows
            // SubmitStrategyOp to correct the situation later, assuming it gets
            // returned by byCommitsOnBranchNotMerged below.
            toWalk.add(commit);
        }

        Set<String> emptySet = Collections.emptySet();
        Set<String> visibleHashes = walkChangesByHashes(visibleCommits, emptySet, or, b);

        List<ChangeData> cds = byCommitsOnBranchNotMerged(or, db, user, b, visibleHashes);
        for (ChangeData chd : cds) {
            chd.changeControl(user);
            visibleChanges.add(chd);
        }

        Set<String> nonVisibleHashes = walkChangesByHashes(nonVisibleCommits, visibleHashes, or, b);
        Iterables.addAll(nonVisibleChanges, byCommitsOnBranchNotMerged(or, db, user, b, nonVisibleHashes));
    }

    return new ChangeSet(visibleChanges, nonVisibleChanges);
}

From source file:org.apache.stratos.cloud.controller.iaases.OpenstackNovaIaas.java

@Override
public synchronized String associateAddress(NodeMetadata node) {

    IaasProvider iaasInfo = getIaasProvider();

    ComputeServiceContext context = iaasInfo.getComputeService().getContext();

    String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);

    RestContext<NovaApi, NovaAsyncApi> nova = context.unwrap();
    FloatingIPApi floatingIp = nova.getApi().getFloatingIPExtensionForZone(region).get();

    String ip = null;/*  ww w  .ja v a 2 s . c  o m*/
    // first try to find an unassigned IP.
    ArrayList<FloatingIP> unassignedIps = Lists
            .newArrayList(Iterables.filter(floatingIp.list(), new Predicate<FloatingIP>() {

                @Override
                public boolean apply(FloatingIP arg0) {
                    return arg0.getInstanceId() == null;
                }

            }));

    if (!unassignedIps.isEmpty()) {
        // try to prevent multiple parallel launches from choosing the same
        // ip.
        Collections.shuffle(unassignedIps);
        ip = Iterables.getLast(unassignedIps).getIp();
    }

    // if no unassigned IP is available, we'll try to allocate an IP.
    if (ip == null || ip.isEmpty()) {
        FloatingIP allocatedFloatingIP = floatingIp.create();
        if (allocatedFloatingIP == null) {
            String msg = "Failed to allocate an IP address.";
            log.error(msg);
            throw new CloudControllerException(msg);
        }
        ip = allocatedFloatingIP.getIp();
    }

    // wait till the fixed IP address gets assigned - this is needed before
    // we associate a public IP
    while (node.getPrivateAddresses() == null) {
        CloudControllerUtil.sleep(1000);
    }

    if (node.getPublicAddresses() != null && node.getPublicAddresses().iterator().hasNext()) {
        log.info("A public IP (" + node.getPublicAddresses().iterator().next()
                + ") is already allocated to the instance [id] : " + node.getId());
        return null;
    }

    int retries = 0;
    //TODO make 5 configurable
    while (retries < 5 && !associateIp(floatingIp, ip, node.getProviderId())) {

        // wait for 5s
        CloudControllerUtil.sleep(5000);
        retries++;
    }

    log.info("Successfully associated an IP address " + ip + " for node with id: " + node.getId());

    return ip;
}

From source file:org.eclipse.hawkbit.rest.exception.ResponseExceptionHandler.java

/**
 * Method for handling exception of type {@link MultipartException} which is
 * thrown in case the request body is not well formed and cannot be
 * deserialized. Called by the Spring-Framework for exception handling.
 *
 * @param request/*www  . j a  va2s  .  c om*/
 *            the Http request
 * @param ex
 *            the exception which occurred
 * @return the entity to be responded containing the exception information
 *         as entity.
 */
@ExceptionHandler(MultipartException.class)
public ResponseEntity<ExceptionInfo> handleMultipartException(final HttpServletRequest request,
        final Exception ex) {

    logRequest(request, ex);

    final List<Throwable> throwables = ExceptionUtils.getThrowableList(ex);
    final Throwable responseCause = Iterables.getLast(throwables);

    if (responseCause.getMessage().isEmpty()) {
        LOG.warn("Request {} lead to MultipartException without root cause message:\n{}",
                request.getRequestURL(), ex.getStackTrace());
    }

    final ExceptionInfo response = createExceptionInfo(new MultiPartFileUploadException(responseCause));
    return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}

From source file:org.sonar.java.checks.verifier.CheckVerifier.java

private static void validateIssue(Multimap<Integer, Map<IssueAttribute, String>> expected,
        List<Integer> unexpectedLines, AnalyzerMessage issue,
        @Nullable RemediationFunction remediationFunction) {
    int line = issue.getLine();
    if (expected.containsKey(line)) {
        Map<IssueAttribute, String> attrs = Iterables.getLast(expected.get(line));
        assertEquals(issue.getMessage(), attrs, IssueAttribute.MESSAGE);
        Double cost = issue.getCost();
        if (cost != null) {
            Preconditions.checkState(remediationFunction != RemediationFunction.CONST,
                    "Rule with constant remediation function shall not provide cost");
            assertEquals(Integer.toString(cost.intValue()), attrs, IssueAttribute.EFFORT_TO_FIX);
        } else if (remediationFunction == RemediationFunction.LINEAR) {
            Fail.fail("A cost should be provided for a rule with linear remediation function");
        }//from  www .  j a  v  a2 s . c  om
        validateAnalyzerMessage(attrs, issue);
        expected.remove(line, attrs);
    } else {
        unexpectedLines.add(line);
    }
}

From source file:org.ambraproject.wombat.controller.ArticleMetadata.java

RevisionMenu getRevisionMenu() throws IOException {
    List<Map<String, ?>> revisionList = factory.articleApi.requestObject(
            ApiAddress.builder("articles").embedDoi(articleId.getDoi()).addToken("revisions").build(),
            List.class);
    OptionalInt displayedNumber = articlePointer.getRevisionNumber();
    revisionList = revisionList.stream().map((Map<String, ?> revision) -> {
        boolean isDisplayedRevision = displayedNumber.isPresent()
                && getRevisionNumber(revision) == displayedNumber.getAsInt();
        return ImmutableMap.<String, Object>builder().putAll(revision).put("isDisplayed", isDisplayedRevision)
                .build();/*from w  w w .j  a va  2 s.c o  m*/
    }).sorted(Comparator.comparing(ArticleMetadata::getRevisionNumber)).collect(Collectors.toList());

    boolean isDisplayingLatestRevision = !revisionList.isEmpty()
            && (Boolean) Iterables.getLast(revisionList).get("isDisplayed");

    return new RevisionMenu(revisionList, isDisplayingLatestRevision);
}

From source file:com.b2international.snowowl.snomed.reasoner.server.classification.external.SnomedExternalReasonerServiceImpl.java

@Override
public String sendExternalRequest(String branchPath, String reasonerId, String userId) {

    try {/*from  w ww.  ja va2  s.  c  o  m*/

        Branch branch = RepositoryRequests.branching().prepareGet(branchPath)
                .build(SnomedDatastoreActivator.REPOSITORY_UUID).execute(getEventBus()).getSync();

        String previousRelease = BranchMetadataResolver.getEffectiveBranchMetadataValue(branch,
                PREVIOUS_RELEASE_METADATA_KEY);
        String shortName = BranchMetadataResolver.getEffectiveBranchMetadataValue(branch,
                SnomedCoreConfiguration.BRANCH_EXTENSION_SHORTNAME_KEY);
        String defaultNamespace = BranchMetadataResolver.getEffectiveBranchMetadataValue(branch,
                SnomedCoreConfiguration.DEFAULT_NAMESPACE);

        String countryAndNamespaceElement = getCountryAndNamespaceElement(shortName, defaultNamespace);

        Rf2ExportResult exportResult = SnomedRequests.rf2().prepareExport().setReleaseType(Rf2ReleaseType.DELTA)
                .setIncludePreReleaseContent(true).setConceptsAndRelationshipsOnly(true).setUserId(userId)
                .setReferenceBranch(branchPath).setRefSetExportLayout(Rf2RefSetExportLayout.COMBINED)
                .setCountryNamespaceElement(countryAndNamespaceElement)
                .build(SnomedDatastoreActivator.REPOSITORY_UUID).execute(getEventBus()).getSync();

        UUID fileId = exportResult.getRegistryId();
        File rf2Delta = fileRegistry.getFile(fileId);

        RequestBody previousReleaseRequestBody = RequestBody.create(MediaType.parse("text/plain"),
                previousRelease);

        RequestBody fileRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), rf2Delta);
        MultipartBody.Part rf2DeltaBody = MultipartBody.Part.createFormData("rf2Delta", rf2Delta.getName(),
                fileRequestBody);

        RequestBody branchPathRequestBody = RequestBody.create(MediaType.parse("text/plain"), branchPath);
        RequestBody reasonerIdRequestBody = RequestBody.create(MediaType.parse("text/plain"), reasonerId);

        LOGGER.info(
                "Sending export results for external classification, branch path: {}, previous release: {}, reasoner: {}",
                branchPath, previousRelease, reasonerId);

        String location = client.sendResults(previousReleaseRequestBody, rf2DeltaBody, branchPathRequestBody,
                reasonerIdRequestBody).fail(fail -> {
                    throw Throwables.propagate(fail);
                }).getSync();

        fileRegistry.delete(fileId);

        return Iterables.getLast(Splitter.on('/').splitToList(location));

    } catch (Exception e) {
        throw new SnowowlRuntimeException("Exception while preparing data for external classification", e);
    }
}

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

static List<GaugeValue> rollUpGaugeValues(List<GaugeValue> orderedNonRolledUpGaugeValues, String gaugeName,
        Function<Long, Long> rollupCaptureTimeFn) {
    List<GaugeValue> rolledUpGaugeValues = Lists.newArrayList();
    double currTotal = 0;
    long currWeight = 0;
    long currRollupCaptureTime = Long.MIN_VALUE;
    for (GaugeValue nonRolledUpGaugeValue : orderedNonRolledUpGaugeValues) {
        long captureTime = nonRolledUpGaugeValue.getCaptureTime();
        long rollupCaptureTime = rollupCaptureTimeFn.apply(captureTime);
        if (rollupCaptureTime != currRollupCaptureTime && currWeight > 0) {
            rolledUpGaugeValues//from w  ww .  j a  v  a2s  .com
                    .add(GaugeValue.newBuilder().setGaugeName(gaugeName).setCaptureTime(currRollupCaptureTime)
                            .setValue(currTotal / currWeight).setWeight(currWeight).build());
            currTotal = 0;
            currWeight = 0;
        }
        currRollupCaptureTime = rollupCaptureTime;
        currTotal += nonRolledUpGaugeValue.getValue() * nonRolledUpGaugeValue.getWeight();
        currWeight += nonRolledUpGaugeValue.getWeight();
    }
    if (currWeight > 0) {
        // roll up final one
        long lastCaptureTime = Iterables.getLast(orderedNonRolledUpGaugeValues).getCaptureTime();
        rolledUpGaugeValues.add(GaugeValue.newBuilder().setGaugeName(gaugeName).setCaptureTime(lastCaptureTime)
                .setValue(currTotal / currWeight).setWeight(currWeight).build());
    }
    return rolledUpGaugeValues;
}

From source file:org.apache.james.jmap.methods.SetMailboxesUpdateProcessor.java

private String getCurrentMailboxName(MailboxPath originMailboxPath, MailboxSession mailboxSession) {
    return Iterables
            .getLast(Splitter.on(mailboxSession.getPathDelimiter()).splitToList(originMailboxPath.getName()));
}

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

private <K> void syncManualRollupCaptureTimes(Map<K, List<SyntheticResult>> map, int rollupLevel) {
    long fixedIntervalMillis = configRepository.getRollupConfigs().get(rollupLevel).intervalMillis();
    Map<K, Long> manualRollupCaptureTimes = Maps.newHashMap();
    long maxCaptureTime = Long.MIN_VALUE;
    for (Map.Entry<K, List<SyntheticResult>> entry : map.entrySet()) {
        List<SyntheticResult> syntheticResults = entry.getValue();
        if (syntheticResults.isEmpty()) {
            continue;
        }//from  w  w  w. ja  v  a  2s.c  o m
        SyntheticResult lastSyntheticResult = Iterables.getLast(syntheticResults);
        long lastCaptureTime = lastSyntheticResult.captureTime();
        maxCaptureTime = Math.max(maxCaptureTime, lastCaptureTime);
        if (lastCaptureTime % fixedIntervalMillis != 0) {
            manualRollupCaptureTimes.put(entry.getKey(), lastCaptureTime);
        }
    }
    if (maxCaptureTime == Long.MIN_VALUE) {
        // nothing to sync
        return;
    }
    long maxRollupCaptureTime = CaptureTimes.getRollup(maxCaptureTime, fixedIntervalMillis);
    long maxDiffToSync = Math.min(fixedIntervalMillis / 5, 60000);
    for (Map.Entry<K, Long> entry : manualRollupCaptureTimes.entrySet()) {
        Long captureTime = entry.getValue();
        if (CaptureTimes.getRollup(captureTime, fixedIntervalMillis) != maxRollupCaptureTime) {
            continue;
        }
        if (maxCaptureTime - captureTime > maxDiffToSync) {
            // only sync up times that are close to each other
            continue;
        }
        K key = entry.getKey();
        List<SyntheticResult> syntheticResults = checkNotNull(map.get(key));
        // make copy in case ImmutableList
        syntheticResults = Lists.newArrayList(syntheticResults);
        SyntheticResult lastSyntheticResult = Iterables.getLast(syntheticResults);
        syntheticResults.set(syntheticResults.size() - 1, ImmutableSyntheticResult.builder()
                .copyFrom(lastSyntheticResult).captureTime(maxCaptureTime).build());
        map.put(key, syntheticResults);
    }
}