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:brooklyn.networking.cloudstack.portforwarding.CloudstackPortForwarder.java

@Override
public void inject(Entity owner, List<Location> locations) {
    subnetTier = (SubnetTier) owner;/*from ww  w .j a  v  a 2 s. c  o m*/
    jcloudsLocation = (JcloudsLocation) Iterables.get(locations, 0);
    client = CloudstackNew40FeaturesClient.newInstance(jcloudsLocation);
}

From source file:com.haulmont.cuba.desktop.gui.data.TreeModelAdapter.java

@Override
public Object getChild(Object parent, int index) {
    Collection<Object> childrenIds;
    if (parent == rootNode) {
        childrenIds = datasource.getRootItemIds();
    } else {//from  w  w w . ja  v a  2 s  .  c  o m
        childrenIds = datasource.getChildren(((Node) parent).getEntity().getId());
    }
    Object id = Iterables.get(childrenIds, index);
    return new Node(parent, datasource.getItem(id));
}

From source file:org.zanata.client.commands.init.ProjectIterationPrompt.java

@VisibleForTesting
protected void selectVersion() {
    Project project = clientFactory.getProjectClient(opts.getProj()).get();
    consoleInteractor.printfln(get("available.versions"), project.getName());
    int oneBasedIndex = 1;
    List<String> versionIndexes = Lists.newArrayList();
    Iterable<ProjectIteration> activeIterations = Iterables.filter(project.getIterations(),
            new ActiveIterationPredicate());
    for (ProjectIteration iteration : activeIterations) {
        versionIndexes.add(oneBasedIndex + "");
        consoleInteractor.printf("%d)", oneBasedIndex).printfln(Hint, iteration.getId());
        oneBasedIndex++;// w w w .java 2 s .c om
    }
    consoleInteractor.printf(Question, get("select.version.prompt"));
    String selection = consoleInteractor.expectAnswerWithRetry(expect(versionIndexes));
    ProjectIteration projectIteration = Iterables.get(activeIterations, (Integer.parseInt(selection) - 1));
    String versionId = projectIteration.getId();
    opts.setProjectVersion(versionId);
    opts.setProjectType(resolveProjectType(project, projectIteration));
}

From source file:org.jclouds.cloudstack.functions.ParseTypedAsyncJob.java

public AsyncJob<?> apply(AsyncJob<Map<String, JsonBall>> toParse) {
    AsyncJob<?> result = toParse;/*  w ww.j  a  v  a 2s . c  o  m*/
    if (toParse.getResult() != null) {
        if (toParse.getResult().size() == 1) {
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Builder<?, Object> builder = AsyncJob.Builder.fromAsyncJobUntyped((AsyncJob) toParse);
            if (toParse.getResult().containsKey("success")) {
                builder.result(null);
            } else {
                Entry<String, JsonBall> entry = Iterables.get(toParse.getResult().entrySet(), 0);
                if ("template".equals(entry.getKey())) {
                    // Sometimes Cloudstack will say 'template' and the payload is a Template object.
                    // Sometimes Cloudstack will say 'template' and the payload is a TemplateExtraction object.
                    // The 'state' field only exists on TemplateExtraction, so we can test this to work out what we have actually been given.
                    Template template = json.fromJson(entry.getValue().toString(), Template.class);
                    TemplateExtraction templateExtraction = json.fromJson(entry.getValue().toString(),
                            TemplateExtraction.class);
                    boolean isTemplate = Strings.isNullOrEmpty(templateExtraction.getState());
                    builder.result(isTemplate ? template : templateExtraction);
                } else if (typeMap.containsKey(entry.getKey())) {
                    builder.result(json.fromJson(entry.getValue().toString(), typeMap.get(entry.getKey())));
                } else {
                    logger.warn(
                            "type key %s not configured.  please override default for Map<String, Class<?>> bound to name jclouds.cloudstack.jobresult-type-map",
                            entry.getKey());
                    builder.result(entry.getValue().toString());
                }
            }
            result = builder.build();
        } else if (toParse.getResult().containsKey("errorcode")) {
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Builder<?, Object> builder = AsyncJob.Builder.fromAsyncJobUntyped((AsyncJob) toParse);
            builder.result(null);// avoid classcastexceptions
            builder.error(AsyncJobError.builder()
                    .errorCode(ErrorCode.fromValue(toParse.getResult().get("errorcode").toString()))
                    .errorText(toParse.getResult().containsKey("errortext")
                            ? toParse.getResult().get("errortext").toString().replace("\"", "")
                            : null)
                    .build());
            result = builder.build();
        } else if (toParse.getResult().size() > 1) {
            logger.warn("unexpected size of async job result; expecting a map with a single element",
                    toParse.getResult());
        }
    }
    return result;
}

From source file:org.apache.lens.server.query.collect.IntersectingWaitingQueriesSelector.java

@VisibleForTesting
Set<QueryContext> findCommonQueries(final List<Set<QueryContext>> candiateQueriesSets) {

    Set<QueryContext> commonQueries = Sets.newLinkedHashSet();

    if (!candiateQueriesSets.isEmpty()) {
        commonQueries = Iterables.get(candiateQueriesSets, 0);

        for (Set<QueryContext> candidateEligibleQueries : candiateQueriesSets) {
            commonQueries.retainAll(candidateEligibleQueries);
        }//  w w  w  .j a v  a  2s.  c o  m
    }
    return commonQueries;
}

From source file:blue.lapis.pore.impl.inventory.PorePlayerInventory.java

@Override
public void setChestplate(ItemStack chestplate) {
    Iterables.get(this.getHandle().query(EquipmentTypes.CHESTPLATE).<Slot>slots(), 0)
            .set(ItemStackConverter.of(chestplate));
}

From source file:org.obm.locator.LocatorClientImpl.java

@Override
public String getServiceLocation(String serviceSlashProperty, String loginAtDomain)
        throws LocatorClientException {
    try {/*w  w w  .j a  v a 2 s .c o m*/
        String responseBody = Request.Get(buildFullServiceUrl(serviceSlashProperty, loginAtDomain))
                .connectTimeout(timeoutInMS).socketTimeout(timeoutInMS).execute().returnContent().asString();
        return Iterables.get(Splitter.on(RESPONSE_SEPARATOR).split(responseBody), 0);
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == HTTP_CODE_NOT_FOUND) {
            throw new ServiceNotFoundException(
                    String.format("Service %s for %s not found", serviceSlashProperty, loginAtDomain));
        } else {
            throw new LocatorClientException(
                    String.format("HTTP error %d: %s", e.getStatusCode(), e.getMessage()), e);
        }
    } catch (MalformedURLException e) {
        throw new LocatorClientException(e.getMessage(), e);
    } catch (SocketTimeoutException e) {
        throw new LocatorClientException(e.getMessage(), e);
    } catch (IOException e) {
        throw new LocatorClientException(e.getMessage(), e);
    }
}

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

private ImmutableMap<BuildTarget, Version> selectVersions(BuildTarget root,
        ImmutableMap<BuildTarget, ImmutableSet<Version>> domain) throws VersionException {

    TargetNode<?, ?> node = targetGraph.get(root);
    ImmutableMap.Builder<BuildTarget, Version> selectedVersions = ImmutableMap.builder();

    Optional<Map.Entry<String, VersionUniverse>> universe = getVersionUniverse(node);
    LOG.verbose("%s: selected universe: %s", root.getBuildTarget(), universe);
    for (Map.Entry<BuildTarget, ImmutableSet<Version>> ent : domain.entrySet()) {
        Version version;//  w ww . j  av  a2s.  c  o m
        if (universe.isPresent()
                && ((version = universe.get().getValue().getVersions().get(ent.getKey())) != null)) {
            if (!ent.getValue().contains(version)) {
                throw new VersionException(root, String.format(
                        "%s has no version %s (specified by universe %s) in available versions: %s", version,
                        ent.getKey(), universe.get().getKey(), Joiner.on(", ").join(ent.getValue())));
            }
        } else {
            version = Iterables.get(ent.getValue(), 0);
        }
        selectedVersions.put(ent.getKey(), version);
    }

    return selectedVersions.build();
}

From source file:org.jclouds.gogrid.compute.strategy.FindIpThenCreateNodeInGroup.java

@Override
public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) {
    Server addedServer = null;/*w w w  .ja v a2s.c o  m*/
    boolean notStarted = true;
    int numOfRetries = 20;
    GetIpListOptions unassignedIps = new GetIpListOptions().onlyUnassigned()
            .inDatacenter(template.getLocation().getId()).onlyWithType(IpType.PUBLIC);
    // lock-free consumption of a shared resource: IP address pool
    while (notStarted) { // TODO: replace with Predicate-based thread
        // collision avoidance for simplicity
        Set<Ip> availableIps = client.getIpServices().getIpList(unassignedIps);
        if (availableIps.isEmpty())
            throw new RuntimeException("No IPs available on this identity.");
        int ipIndex = new SecureRandom().nextInt(availableIps.size());
        Ip availableIp = Iterables.get(availableIps, ipIndex);
        try {
            addedServer = addServer(name, template, availableIp);
            notStarted = false;
        } catch (Exception e) {
            if (--numOfRetries == 0)
                Throwables.propagate(e);
            notStarted = true;
        }
    }
    if (template.getOptions().shouldBlockUntilRunning()) {
        serverLatestJobCompleted.apply(addedServer);
        client.getServerServices().power(addedServer.getName(), PowerCommand.START);
        serverLatestJobCompletedShort.apply(addedServer);
        addedServer = Iterables
                .getOnlyElement(client.getServerServices().getServersByName(addedServer.getName()));
    }
    credentialStore.put("node#" + addedServer.getId(),
            client.getServerServices().getServerCredentialsList().get(addedServer.getName()));
    return serverToNodeMetadata.apply(addedServer);
}

From source file:com.facebook.presto.sql.planner.plan.UnionNode.java

/**
 * Returns the output to input symbol mapping for the given source channel
 *//* w  w  w  .  j a v  a2 s  .c  o m*/
public Map<Symbol, QualifiedNameReference> sourceSymbolMap(int sourceIndex) {
    ImmutableMap.Builder<Symbol, QualifiedNameReference> builder = ImmutableMap
            .<Symbol, QualifiedNameReference>builder();
    for (Map.Entry<Symbol, Collection<Symbol>> entry : symbolMapping.asMap().entrySet()) {
        builder.put(entry.getKey(), Iterables.get(entry.getValue(), sourceIndex).toQualifiedNameReference());
    }

    return builder.build();
}