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.renjin.primitives.special.SwitchFunction.java

private static SEXP doApply(Context context, Environment rho, FunctionCall call, PairList args) {
    EvalException.check(call.length() > 1, "argument \"EXPR\" is missing");

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

    Iterable<PairList.Node> branches = Iterables.skip(args.nodes(), 1);

    if (expr instanceof StringVector) {
        String name = ((StringVector) expr).getElementAsString(0);
        if (StringVector.isNA(name)) {
            context.setInvisibleFlag();//from   ww w .j  a va 2s.c  om
            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);
        }
    }
    // no match
    return Null.INSTANCE;
}

From source file:org.sosy_lab.cpachecker.cpa.predicate.persistence.PredicatePersistenceUtils.java

public static Pair<String, List<String>> splitFormula(FormulaManagerView fmgr, BooleanFormula f) {
    StringBuilder fullString = new StringBuilder();
    Appenders.appendTo(fullString, fmgr.dumpFormula(f));
    List<String> lines = LINE_SPLITTER.splitToList(fullString);

    String formulaString;/*ww w.  java 2  s.co m*/
    List<String> declarations;

    if (lines.isEmpty()) {
        if (fmgr.getBooleanFormulaManager().isTrue(f)) {
            declarations = Collections.emptyList();
            formulaString = "(assert true)";
        } else {
            throw new AssertionError();
        }
    } else {
        declarations = lines.subList(0, lines.size() - 1);
        formulaString = Iterables.getLast(lines);
    }

    assert formulaString.startsWith("(assert ") && formulaString.endsWith(")") : "Unexpected formula format: "
            + formulaString;

    return Pair.of(formulaString, declarations);
}

From source file:is.illuminati.block.spyros.garmin.model.Track.java

/** 
 * Get end time of track.
 * @return the end time.
 */
public DateTime getEndTime() {
    return Iterables.getLast(trackPoints).getTime();
}

From source file:org.sonar.pickbasic.checks.SwitchWithoutDefaultCheck.java

@Override
public void visitSwitchStatement(SwitchStatementTree tree) {
    if (!hasDefaultCase(tree)) {
        getContext().addIssue(this, tree, ADD_DEFAULT_MESSAGE);

    } else if (!Iterables.getLast(tree.cases()).is(Kind.DEFAULT_CLAUSE)) {
        getContext().addIssue(this, tree, MOVE_DEFAULT_MESSAGE);
    }/*from ww  w  .  jav  a  2  s .c om*/
    super.visitSwitchStatement(tree);
}

From source file:org.kitesdk.data.spi.filesystem.FileSystemDatasets.java

/**
 * Convert a URI for a partition directory in a filesystem dataset to a {@link View}
 * object representing that partition.//from  w w  w.  j av  a  2  s . c om
 * @param dataset the (partitioned) filesystem dataset
 * @param uri the path to the partition directory
 * @return a view of the partition
 */
public static <E> View<E> viewForUri(Dataset<E> dataset, URI uri) {
    Preconditions.checkArgument(dataset instanceof FileSystemDataset, "Not a file system dataset: " + dataset);

    DatasetDescriptor descriptor = dataset.getDescriptor();

    String s1 = descriptor.getLocation().getScheme();
    String s2 = uri.getScheme();
    Preconditions.checkArgument((s1 == null || s2 == null) || s1.equals(s2), "%s is not contained in %s", uri,
            descriptor.getLocation());

    URI location = URI.create(descriptor.getLocation().getPath());
    URI relative = location.relativize(URI.create(uri.getPath()));
    if (relative.toString().isEmpty()) {
        // no partitions are selected
        return dataset;
    }

    Preconditions.checkArgument(!relative.getPath().startsWith("/"), "%s is not contained in %s", uri,
            location);
    Preconditions.checkArgument(descriptor.isPartitioned(), "Dataset is not partitioned");

    Schema schema = descriptor.getSchema();
    PartitionStrategy strategy = descriptor.getPartitionStrategy();

    RefinableView<E> view = dataset;
    Iterator<String> parts = PATH_SPLITTER.split(relative.toString()).iterator();
    for (FieldPartitioner fp : Accessor.getDefault().getFieldPartitioners(strategy)) {
        if (!parts.hasNext()) {
            break;
        }
        String value = Iterables.getLast(KV_SPLITTER.split(parts.next()));
        Schema fieldSchema = SchemaUtil.fieldSchema(schema, strategy, fp.getName());
        view = view.with(fp.getName(), Conversions.convert(value, fieldSchema));
    }
    return view;
}

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

@Override
public void visitNode(Tree tree) {
    LambdaExpressionTree lambdaExpressionTree = (LambdaExpressionTree) tree;
    List<VariableTree> parameters = lambdaExpressionTree.parameters();
    if (parameters.size() <= 2 && !lambdaExpressionTree.body().is(Tree.Kind.BLOCK)) {
        // ignore lambdas with one or two params and a non-block body
        return;/*w  w  w  .  j  a  va2s .c  o  m*/
    }
    String missingTypeParameters = parameters.stream()
            .filter(variable -> variable.type().is(Tree.Kind.INFERED_TYPE)).map(VariableTree::simpleName)
            .map(IdentifierTree::name).map(parameterName -> "'" + parameterName + "'")
            .collect(Collectors.joining(", "));

    if (!missingTypeParameters.isEmpty()) {
        reportIssue(parameters.get(0), Iterables.getLast(parameters),
                String.format("Specify a type for: %s", missingTypeParameters));
    }
}

From source file:org.richfaces.services.ServiceLoader.java

public static <S> S loadService(Class<S> serviceClass) {
    Collection<Class<? extends S>> serviceClasses = loadServiceClasses(serviceClass);
    try {// w  w  w  . ja v  a  2s .  c  o  m
        return createInstance(Iterables.getLast(serviceClasses));
    } catch (NoSuchElementException e) {
        return null;
    }
}

From source file:com.google.api.tools.framework.aspects.http.MethodMatcher.java

public MethodMatcher(MethodPattern pattern, Method method, HttpAttribute httpConfig) {
    this.pattern = pattern;
    this.method = method;
    this.httpConfig = httpConfig;

    matches = false;//from ww w .j  a v  a2  s .c  om

    // Check http method.
    if (httpConfig.getMethodKind() != pattern.httpMethod()) {
        return;
    }

    // Check name regexp.
    nameMatcher = pattern.nameRegexp().matcher(method.getSimpleName());
    if (!nameMatcher.matches()) {
        return;
    }

    // Determine match on last segment.
    List<PathSegment> flatPath = httpConfig.getFlatPath();
    PathSegment lastSegment = Iterables.getLast(flatPath);
    switch (pattern.lastSegmentPattern()) {
    case CUSTOM_VERB_WITH_COLON:
        // Allow only standard conforming custom method which uses <prefix>:<literal>.
        matches = lastSegment instanceof LiteralSegment
                && ((LiteralSegment) lastSegment).isTrailingCustomVerb();
        break;
    case CUSTOM_VERB:
        // Allow both a custom verb literal and a regular literal, the latter is for supporting
        // legacy custom verbs.
        matches = lastSegment instanceof LiteralSegment;
        break;
    case VARIABLE:
        matches = lastSegment instanceof WildcardSegment;
        break;
    case LITERAL:
        matches = lastSegment instanceof LiteralSegment
                && !((LiteralSegment) lastSegment).isTrailingCustomVerb();
        break;
    }
}

From source file:org.sonar.javascript.checks.SwitchWithoutDefaultCheck.java

@Override
public void visitSwitchStatement(SwitchStatementTree tree) {
    if (!hasDefaultCase(tree)) {
        addLineIssue(tree, ADD_DEFAULT_MESSAGE);

    } else if (!Iterables.getLast(tree.cases()).is(Kind.DEFAULT_CLAUSE)) {
        addLineIssue(tree, MOVE_DEFAULT_MESSAGE);
    }//from w  ww  . j a va 2 s  .co  m
    super.visitSwitchStatement(tree);
}

From source file:org.cicomponents.github.impl.GithubOAuthTokenProvisioner.java

@SneakyThrows
@Override/*from  ww w  . ja  va  2  s.  c  o m*/
public void finalizeOAuth(UUID uuid, String code) {
    Collection<OAuthTokenProvider> providers = registrations.get(uuid);
    providers.forEach(new Consumer<OAuthTokenProvider>() {
        @SneakyThrows
        @Override
        public void accept(OAuthTokenProvider p) {
            p.setToken(p.getService().getAccessToken(code));
        }
    });
    ArrayList<String> tokens = new ArrayList<>(
            providers.stream().map(OAuthTokenProvider::getAccessToken).collect(Collectors.toList()));
    persistentMap.put(Iterables.getLast(providers).getCredentialsProvider().getClientId(), tokens);
    Collection<ServiceRegistration<GithubOAuthTokenProvider>> registrations = registerProviders(providers);
    this.registrations.remove(uuid);
    tokenProviders.addAll(registrations);
    providers.forEach(p -> pendingProvisioning.remove(p.getCredentialsProvider().getClientId()));
}