Example usage for com.google.common.collect Iterables get

List of usage examples for com.google.common.collect Iterables get

Introduction

In this page you can find the example usage for com.google.common.collect Iterables get.

Prototype

public static <T> T get(Iterable<T> iterable, int position) 

Source Link

Document

Returns the element at the specified position in an iterable.

Usage

From source file:com.facebook.buck.versions.VersionUniverseVersionSelector.java

@VisibleForTesting
protected Optional<Map.Entry<String, VersionUniverse>> getVersionUniverse(TargetNode<?, ?> root) {
    Optional<String> universeName = getVersionUniverseName(root);
    if (!universeName.isPresent() && !universes.isEmpty()) {
        return Optional.of(Iterables.get(universes.entrySet(), 0));
    }/*from  w  w w.ja  v a  2 s.co m*/
    if (!universeName.isPresent()) {
        return Optional.empty();
    }
    VersionUniverse universe = universes.get(universeName.get());
    if (universe == null) {
        throw new VerifyException(String.format("%s: unknown version universe \"%s\"", root.getBuildTarget(),
                universeName.get()));
    }
    return Optional.of(new AbstractMap.SimpleEntry<>(universeName.get(), universe));
}

From source file:org.fuusio.api.nfc.SmartPosterRecord.java

/**
 * Returns the first element of {@code elements} which is an instance of {@code type}, or
 * {@code null} if no such element exists.
 *///  w  w w. jav a2 s  . co m
private static <T> T getFirstIfExists(final Iterable<?> elements, final Class<T> type) {
    final Iterable<T> filtered = Iterables.filter(elements, type);
    T instance = null;

    if (!Iterables.isEmpty(filtered)) {
        instance = Iterables.get(filtered, 0);
    }
    return instance;
}

From source file:com.eucalyptus.cloudwatch.common.CloudWatchResourceName.java

public static CloudWatchResourceName parse(final String resourceName, @Nullable final Type type)
        throws InvalidResourceNameException {
    if (!resourceName.startsWith(prefix)) {
        throw new InvalidResourceNameException(resourceName);
    }/*  w w  w. j  ava2  s.  com*/

    final Iterable<String> nameParts = nameSpliter.split(resourceName);
    final int namePartCount = Iterables.size(nameParts);
    if (namePartCount < MIN_PARTS || namePartCount > MAX_PARTS) {
        throw new InvalidResourceNameException(resourceName);
    }

    if (!"cloudwatch".equals(Iterables.get(nameParts, PART_SERVICE))) {
        throw new InvalidResourceNameException(resourceName);
    }

    if (type != null && !type.name().equals(Iterables.get(nameParts, PART_RELATIVE_ID_TYPE))) {
        throw new InvalidResourceNameException(resourceName);
    }

    return new CloudWatchResourceName(resourceName, Iterables.get(nameParts, PART_SERVICE),
            Iterables.get(nameParts, PART_NAMESPACE), Iterables.get(nameParts, PART_RELATIVE_ID_TYPE),
            Iterables.get(nameParts, PART_RELATIVE_NAME));
}

From source file:com.cinchapi.concourse.util.Timestamps.java

/**
 * Search the chronological set of {@code timestamps} to return the index of
 * a contained timestamp that occurs on or after the {@code sought}
 * timestamp and more closely than any others.
 * <p>//from w  w w.j av  a  2s .c o  m
 * <ul>
 * <li>If the search set is empty, this function will return {@code 0}</li>
 * <li>If the sought timestamp is smaller than every timestamp in the search
 * set, this function will return {@code 0}</li>
 * <li>If the sought timestamp is greater than every timestamp in the search
 * set, this function will return the size of the search set, which is 1
 * greater than the last index in the search set</li>
 * </ul>
 * </p>
 * 
 * @param timestamps
 * @param sought
 * @return an index of nearest successor timestamp
 */
public static int findNearestSuccessorForTimestamp(Set<Long> timestamps, long sought) {
    int start = 0;
    int end = timestamps.size() - 1;
    while (start <= end) {
        int mid = (start + end) / 2;
        long stored = Iterables.get(timestamps, mid);
        if (sought == stored) {
            return mid;
        } else if (sought > stored) {
            start = mid + 1;
        } else {
            end = mid - 1;
        }
    }
    return start;
}

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 www.  j a va2 s .com*/
            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:com.eucalyptus.network.applicator.ModeSpecificApplicator.java

private NetworkMode extractMode(final NetworkInfo networkInfo) {
    final Optional<NIProperty> property = networkInfo.getConfiguration().getProperties().stream()
            .filter(prop -> "mode".equals(prop.getName())).findFirst();

    return NetworkMode.fromString(property.map(prop -> Iterables.get(prop.getValues(), 0)).orElse(null),
            NetworkMode.EDGE);/* w w  w  .  jav a  2 s  . c  o  m*/
}

From source file:fr.putnami.pwt.core.model.client.model.ModelCollection.java

@Override
protected <P> P internalGet(Collection<T> list, String fieldName) {
    int index = Integer.parseInt(fieldName);
    return (P) Iterables.get(list, index);
}

From source file:com.ibm.common.geojson.GeometryCollection.java

@SuppressWarnings("unchecked")
public <G extends Geometry<?, ?>> G get(int idx) {
    return (G) Iterables.get(geometries(), idx);
}

From source file:org.jclouds.rackspace.cloudloadbalancers.functions.ConvertLB.java

@Override
public LoadBalancer apply(LB lb) {
    try {/*from   ww  w. java2s  .co m*/
        Builder builder = LoadBalancer.builder().id(lb.id).region(region).status(lb.status).name(lb.getName())
                .protocol(lb.getProtocol()).port(lb.getPort()).nodeCount(lb.nodeCount).nodes(lb.getNodes())
                .timeout(lb.getTimeout()).algorithm(lb.getAlgorithm()).halfClosed(lb.isHalfClosed())
                .sessionPersistenceType(lb.getSessionPersistenceType())
                .connectionLogging(lb.isConnectionLogging()).connectionThrottle(lb.getConnectionThrottle())
                .healthMonitor(lb.getHealthMonitor());

        if (lb.cluster.size() == 1)
            builder.clusterName(Iterables.get(lb.cluster.values(), 0));
        if (lb.created.size() == 1)
            builder.created(Iterables.get(lb.created.values(), 0));
        if (lb.updated.size() == 1)
            builder.updated(Iterables.get(lb.updated.values(), 0));
        if (lb.contentCaching.size() == 1)
            builder.contentCaching(Iterables.get(lb.contentCaching.values(), 0));
        if (lb.sslTermination != null)
            builder.sslTermination(lb.sslTermination);
        if (lb.sourceAddresses != null)
            builder.sourceAddresses(lb.sourceAddresses);
        if (lb.accessList == null)
            builder.accessRules(ImmutableSet.<AccessRuleWithId>of());
        else
            builder.accessRules(lb.accessList);
        if (lb.virtualIps == null)
            builder.virtualIPs(ImmutableSet.<VirtualIPWithId>of());
        else
            builder.virtualIPs(lb.virtualIps);
        if (lb.metadata == null)
            builder.metadata(new Metadata());
        else
            builder.metadata(ParseMetadata.transformCLBMetadataToMetadata(lb.metadata));

        return builder.build();
    } catch (NullPointerException e) {
        logger.warn(e, "nullpointer found parsing %s", lb);
        throw e;
    }
}

From source file:com.ibm.common.geojson.FeatureCollection.java

public Feature get(int idx) {
    return Iterables.get(features(), idx);
}