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.jclouds.trmk.vcloud_0_8.binders.OrgNameAndVDCNameToEndpoint.java

@SuppressWarnings("unchecked")
@Override/*from   w ww .ja v a2 s  . c o m*/
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
    Object org = postParams.get("orgName");
    Object vdc = postParams.get("vdcName");
    if (org == null && vdc == null)
        return (R) request.toBuilder().endpoint(defaultVDC.get().getHref()).build();
    else if (org == null)
        org = defaultOrg.get().getName();

    try {
        Map<String, ReferenceType> vdcs = checkNotNull(orgNameToVDCEndpoint.get().get(org)).getVDCs();
        URI endpoint = vdc == null ? Iterables.getLast(vdcs.values()).getHref() : vdcs.get(vdc).getHref();
        return (R) request.toBuilder().endpoint(endpoint).build();
    } catch (NullPointerException e) {
        throw new NoSuchElementException(org + "/" + vdc + " not found in " + orgNameToVDCEndpoint.get());
    }
}

From source file:com.google.api.codegen.transformer.ruby.RubyPackageMetadataNamer.java

private String getSimpleMetadataIdentifier() {
    return Iterables.getLast(Splitter.on(METADATA_IDENTIFIER_SEPARATOR).split(getMetadataIdentifier()));
}

From source file:org.jclouds.trmk.vcloud_0_8.binders.OrgNameAndTasksListNameToEndpoint.java

@SuppressWarnings("unchecked")
@Override/*from  w ww .  j a  v  a2 s.  co m*/
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
    Object org = postParams.get("orgName");
    Object tasksList = postParams.get("tasksListName");
    if (org == null && tasksList == null)
        return (R) request.toBuilder().endpoint(defaultTasksList.get().getHref()).build();
    else if (org == null)
        org = defaultOrg.get().getName();

    try {
        Map<String, ReferenceType> tasksLists = checkNotNull(orgMap.get().get(org)).getTasksLists();
        URI endpoint = tasksList == null ? Iterables.getLast(tasksLists.values()).getHref()
                : tasksLists.get(tasksList).getHref();
        return (R) request.toBuilder().endpoint(endpoint).build();
    } catch (NullPointerException e) {
        throw new NoSuchElementException(org + "/" + tasksList + " not found in " + orgMap.get());
    }
}

From source file:org.jclouds.vcloud.director.v1_5.functions.OrgNameAndCatalogNameToEndpoint.java

@SuppressWarnings("unchecked")
public URI apply(Object from) {
    Iterable<Object> orgCatalog = (Iterable<Object>) checkNotNull(from, "args");
    Object org = Iterables.get(orgCatalog, 0);
    Object catalog = Iterables.get(orgCatalog, 1);
    if (org == null && catalog == null)
        return defaultCatalog.get().getHref();
    else if (org == null)
        org = defaultOrg.get().getName();

    try {/*w  w w.j a  v a 2 s  .  c o m*/
        Set<Reference> catalogs = checkNotNull(orgMap.get().get(org)).getCatalogs();
        return catalog == null ? Iterables.getLast(catalogs).getHref()
                : Iterables.find(catalogs, nameEquals((String) catalog)).getHref();
    } catch (NullPointerException e) {
        throw new NoSuchElementException(org + "/" + catalog + " not found in " + orgMap.get());
    }
}

From source file:org.jclouds.vcloud.director.v1_5.functions.OrgNameAndVdcNameToEndpoint.java

@SuppressWarnings("unchecked")
public URI apply(Object from) {
    Iterable<Object> orgVdc = (Iterable<Object>) checkNotNull(from, "args");
    Object org = Iterables.get(orgVdc, 0);
    Object vdc = Iterables.get(orgVdc, 1);
    if (org == null && vdc == null)
        return defaultVdc.get().getHref();
    else if (org == null)
        org = defaultOrg.get().getName();

    try {//from  w ww  .j av a2s .  co  m
        Set<Reference> vdcs = checkNotNull(orgNameToVdcEndpoint.get().get(org)).getVdcs();
        return vdc == null ? Iterables.getLast(vdcs).getHref()
                : Iterables.find(vdcs, nameEquals((String) vdc)).getHref();
    } catch (NullPointerException e) {
        throw new NoSuchElementException(org + "/" + vdc + " not found in " + orgNameToVdcEndpoint.get());
    }
}

From source file:org.sonar.java.checks.LeftCurlyBraceBaseTreeVisitor.java

@CheckForNull
private static SyntaxToken getLastTokenFromSignature(ClassTree classTree) {
    List<TypeTree> superInterfaces = classTree.superInterfaces();
    if (!superInterfaces.isEmpty()) {
        return getIdentifierToken(Iterables.getLast(superInterfaces));
    }//from   w  ww.jav  a  2  s  . co m
    TypeTree superClass = classTree.superClass();
    if (superClass != null) {
        return getIdentifierToken(superClass);
    }
    TypeParameters typeParameters = classTree.typeParameters();
    if (!typeParameters.isEmpty()) {
        return typeParameters.closeBracketToken();
    }
    IdentifierTree simpleName = classTree.simpleName();
    if (simpleName != null) {
        return simpleName.identifierToken();
    }
    // enum constants and new class trees are handled separately
    return null;
}

From source file:org.eclipse.che.ide.ext.svn.client.importer.SubversionProjectImporterPresenter.java

/** {@inheritDoc} */
@Override/*from  www .j a v a  2  s  .c om*/
public void onProjectUrlChanged() {
    if (Strings.isNullOrEmpty(view.getProjectUrl())) {
        view.setProjectName("");
        return;
    }

    String projectName = Iterables.getLast(Splitter.on("/").omitEmptyStrings().split(view.getProjectUrl()));
    String calcUrl = getUrl(view.getProjectUrl(), view.getProjectRelativePath());

    view.setProjectName(projectName);
    dataObject.getSource().getProject().setLocation(calcUrl);
    updateDelegate.updateControls();
}

From source file:com.twitter.aurora.scheduler.storage.StorageBackfill.java

private static void guaranteeShardUniqueness(ScheduledTask task, TaskStore.Mutable taskStore, Clock clock) {

    if (Tasks.isActive(task.getStatus())) {
        // Perform a sanity check on the number of active shards.
        TaskConfig config = task.getAssignedTask().getTask();
        Query.Builder query = Query.instanceScoped(
                JobKeys.from(config.getOwner().getRole(), config.getEnvironment(), config.getJobName()),
                task.getAssignedTask().getInstanceId()).active();
        Set<String> activeTasksInShard = FluentIterable.from(taskStore.fetchTasks(query))
                .transform(Tasks.SCHEDULED_TO_ID).toSet();

        if (activeTasksInShard.size() > 1) {
            SHARD_SANITY_CHECK_FAILS.incrementAndGet();
            LOG.severe("Active shard sanity check failed when loading " + Tasks.id(task)
                    + ", active tasks found: " + activeTasksInShard);

            // We want to keep exactly one task from this shard, so sort the IDs and keep the
            // highest (newest) in the hopes that it is legitimately running.
            String newestTask = Iterables.getLast(Sets.newTreeSet(activeTasksInShard));
            if (!Tasks.id(task).equals(newestTask)) {
                task.setStatus(ScheduleStatus.KILLED);
                task.addToTaskEvents(new TaskEvent(clock.nowMillis(), ScheduleStatus.KILLED)
                        .setMessage("Killed duplicate shard."));
                // TODO(wfarner); Circle back if this is necessary.  Currently there's a race
                // condition between the time the scheduler is actually available without hitting
                // IllegalStateException (see DriverImpl).
                // driver.killTask(Tasks.id(task));
            } else {
                LOG.info("Retaining task " + Tasks.id(task));
            }/*ww w.  j a  v  a 2s .  co m*/
        }
    }
}

From source file:r.base.special.SwitchFunction.java

@Override
public SEXP apply(Context context, Environment rho, FunctionCall call, PairList args) {
    EvalException.check(call.length() > 1, "argument \"EXPR\" is missing");

    SEXP expr = context.evaluate(call.getArgument(0), rho);
    EvalException.check(expr.length() == 1, "EXPR must return a length 1 vector");

    PromisePairList branchPromises = (PromisePairList) context.evaluate(call.getArgument(1), rho);
    Iterable<PairList.Node> branches = branchPromises.nodes();

    if (expr instanceof StringVector) {
        String name = ((StringVector) expr).getElementAsString(0);
        if (StringVector.isNA(name)) {
            context.setInvisibleFlag();/*from   www.j a v a  2 s .co  m*/
            return Null.INSTANCE;
        }
        SEXP partialMatch = null;
        int partialMatchCount = 0;
        for (PairList.Node node : branches) {
            if (node.hasTag()) {
                String branchName = node.getTag().getPrintName();
                if (branchName.equals(name)) {
                    return context.evaluate(nextNonMissing(node), rho);
                } else if (branchName.startsWith(name)) {
                    partialMatch = nextNonMissing(node);
                    partialMatchCount++;
                }
            }
        }
        if (partialMatchCount == 1) {
            return context.evaluate(partialMatch, rho);
        } else if (Iterables.size(branches) > 0) {
            PairList.Node last = Iterables.getLast(branches);
            if (!last.hasTag()) {
                return context.evaluate(last.getValue(), rho);
            }
        }

    } else if (expr instanceof AtomicVector) {
        int branchIndex = ((AtomicVector) expr).getElementAsInt(0);
        if (branchIndex >= 1 && branchIndex <= Iterables.size(branches)) {
            return context.evaluate(Iterables.get(branches, branchIndex - 1).getValue(), rho);
        }
    }

    return Null.INSTANCE;
}

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

@Override
public Description matchMethodInvocation(MethodInvocationTree invocationTree, final VisitorState state) {
    if (!ARRAY_FILL_MATCHER.matches(invocationTree, state)) {
        return Description.NO_MATCH;
    }//from   w w w.  j  a v  a2s .  c  om

    Type arrayComponentType = state.getTypes()
            .elemtype(ASTHelpers.getType(invocationTree.getArguments().get(0)));
    Tree fillingArgument = Iterables.getLast(invocationTree.getArguments());
    Type fillingObjectType = ASTHelpers.getType(fillingArgument);

    // You can put an Integer or an int into a Number[], but you can't put a Number into an
    // Integer[].
    // (Note that you can assign Integer[] to Number[] and then try to put the Number into it, but
    // that's a hole provided by array covariance we can't plug here)
    if (isValidArrayFill(state, arrayComponentType, fillingObjectType)) {
        return Description.NO_MATCH;
    }

    // Due to some funky behavior, javac doesn't appear to fully expand the type of a ternary
    // when passed into an "Object" context. Let's explore both sides
    if (fillingArgument.getKind() == Kind.CONDITIONAL_EXPRESSION) {
        ConditionalExpressionTree cet = (ConditionalExpressionTree) fillingArgument;
        Type trueExpressionType = ASTHelpers.getType(cet.getTrueExpression());
        if (!isValidArrayFill(state, arrayComponentType, trueExpressionType)) {
            return reportMismatch(invocationTree, arrayComponentType, trueExpressionType);
        }

        Type falseExpressionType = ASTHelpers.getType(cet.getFalseExpression());
        if (!isValidArrayFill(state, arrayComponentType, falseExpressionType)) {
            return reportMismatch(invocationTree, arrayComponentType, falseExpressionType);
        }

        // Looks like we were able to find a ternary that would actually work
        return Description.NO_MATCH;
    }

    return reportMismatch(invocationTree, arrayComponentType, fillingObjectType);
}