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:org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection.java

@Override
public Optional<Object> nextMarker() {
    return FluentIterable.from(getLinks()).filter(new Predicate<Link>() {
        @Override/*from  w  w  w. j  a  va  2 s . c  om*/
        public boolean apply(Link link) {
            return Link.Relation.NEXT == link.getRelation();
        }
    }).transform(new Function<Link, Optional<Object>>() {
        @Override
        public Optional<Object> apply(Link link) {
            Collection<String> markers = queryParser().apply(link.getHref().getRawQuery()).get("marker");
            return Optional.<Object>fromNullable(markers == null ? null : Iterables.get(markers, 0));
        }
    }).first().or(Optional.absent());
}

From source file:brooklyn.entity.container.docker.application.DockerServiceTypeResolver.java

@Override
public <T extends Entity> void decorateSpec(BrooklynComponentTemplateResolver resolver, EntitySpec<T> spec) {
    String dockerServiceType = Strings.removeFromStart(resolver.getDeclaredType(), PREFIX + ":");
    List<String> parts = Splitter.on(":").splitToList(dockerServiceType);
    if (parts.isEmpty() || parts.size() > 2) {
        throw new IllegalArgumentException("Docker serviceType cannot be parsed: " + dockerServiceType);
    }/*from ww w . ja  v  a 2 s.  com*/
    String imageName = Iterables.get(parts, 0);
    String imageTag = Iterables.get(parts, 1, "latest");
    log.debug("Creating Docker service entity with image {} and tag {}", imageName, imageTag);
    spec.configure(DockerAttributes.DOCKER_IMAGE_NAME, imageName);
    if (parts.size() == 2) {
        spec.configure(DockerAttributes.DOCKER_IMAGE_TAG, imageTag);
    }
    if (resolver.getAttrs().containsKey("id")) {
        String containerName = (String) resolver.getAttrs().getStringKey("id");
        spec.configure(DockerAttributes.DOCKER_CONTAINER_NAME, containerName);
    }
    super.decorateSpec(resolver, spec);
}

From source file:info.gehrels.voting.web.VoteBuilder.java

private Vote<GenderedCandidate> createPreferenceVote(GenderedElection genderedElection) {
    Builder<GenderedCandidate> preferenceBuilder = ImmutableSet.builder();
    for (char c : preferenceString.toUpperCase().toCharArray()) {
        int candidateIndex = c - 'A';
        preferenceBuilder.add(Iterables.get(genderedElection.getCandidates(), candidateIndex));
    }//from w w w.  j a  va  2s . c  o  m
    return Vote.createPreferenceVote(genderedElection, preferenceBuilder.build());
}

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

@Override
public LoadBalancer apply(LB lb) {
    try {//from   w  w w .  j ava2  s. c  o 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));

        int indexOfLB = endpoint.toString().lastIndexOf(LOAD_BALANCERS);
        String path = endpoint.toString().substring(0, indexOfLB + LOAD_BALANCERS.length());
        builder.uri(URI.create(path + "/" + lb.id));

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

From source file:org.sonar.data.issues.IssueData.java

protected IssueDto getIssue(int id) {
    RuleDto rule = rules.get(generator.nextInt(rules.size()));
    Long projectId = Iterables.get(projects.keySet(), generator.nextInt(projects.size()));
    Long resourceId = projects.get(projectId).get(generator.nextInt(projects.get(projectId).size()));
    return new IssueDto().setId(new Long(id)).setRootComponentId(projectId)
            .setRootComponentKey(projectId + "_key").setComponentId(resourceId)
            .setComponentKey(resourceId + "_key").setRule(rule)
            .setMessage("Lorem ipsum loertium bortim tata toto tutu 14 failures in this issue")
            .setAssignee("assignee_").setSeverity("BLOCKER").setReporter("Luc besson").setAuthorLogin("Pinpin")
            .setStatus("OPEN").setResolution("OPEN").setKee(UUID.randomUUID().toString());
}

From source file:org.springframework.xd.ec2.cloud.AWSTools.java

private List<String> getInstanceIdsByClusterName(String name) {
    ArrayList<String> instanceList = new ArrayList<String>();

    Set<? extends Reservation<? extends AWSRunningInstance>> reservations = client.getInstanceApi().get()
            .describeInstancesInRegion(region);
    int instanceCount = reservations.size();
    for (int x = 0; x < instanceCount; x++) {
        Reservation<? extends AWSRunningInstance> instances = Iterables.get(reservations, x);
        int groupCount = instances.size();
        for (int y = 0; y < groupCount; y++) {
            RunningInstance ri = Iterables.get(instances, y);
            if (ri.getTags().containsKey("Name")) {
                if (ri.getTags().get("Name").equals(name)) {
                    instanceList.add(ri.getId());
                }/*from  ww  w  .  ja  v  a2  s  .c  o m*/
            }
        }
    }
    return instanceList;
}

From source file:org.spongepowered.common.data.processor.data.item.CoalDataProcessor.java

@Override
protected Optional<CoalType> getVal(ItemStack itemStack) {
    return Optional
            .of(Iterables.get(SpongeImpl.getRegistry().getAllOf(CoalType.class), itemStack.getMetadata()));
}

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

@JsonCreator
public UnionNode(@JsonProperty("id") PlanNodeId id, @JsonProperty("sources") List<PlanNode> sources,
        @JsonProperty("symbolMapping") ListMultimap<Symbol, Symbol> symbolMapping) {
    super(id);/*  ww  w. ja v  a 2 s  .  c  o m*/

    requireNonNull(sources, "sources is null");
    checkArgument(!sources.isEmpty(), "Must have at least one source");
    requireNonNull(symbolMapping, "symbolMapping is null");

    this.sources = ImmutableList.copyOf(sources);
    this.symbolMapping = ImmutableListMultimap.copyOf(symbolMapping);

    for (Collection<Symbol> symbols : this.symbolMapping.asMap().values()) {
        checkArgument(symbols.size() == this.sources.size(),
                "Every source needs to map its symbols to an output UNION symbol");
    }

    // Make sure each source positionally corresponds to their Symbol values in the Multimap
    for (int i = 0; i < sources.size(); i++) {
        for (Collection<Symbol> symbols : this.symbolMapping.asMap().values()) {
            checkArgument(sources.get(i).getOutputSymbols().contains(Iterables.get(symbols, i)),
                    "Source does not provide required symbols");
        }
    }
}

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

@Override
public Hardware apply(VAppTemplate from) {
    checkNotNull(from, "VAppTemplate");

    Envelope ovf = templateToEnvelope.apply(from);

    if (ovf.getVirtualSystem().getVirtualHardwareSections().size() > 1) {
        logger.warn("multiple hardware choices found. using first", ovf);
    }// w w w. j  a  v  a2 s .  c om
    VirtualHardwareSection hardware = Iterables.get(ovf.getVirtualSystem().getVirtualHardwareSections(), 0);
    HardwareBuilder builder = rasdToHardwareBuilder.apply(hardware.getItems());
    Link vdc = Iterables.find(checkNotNull(from, "from").getLinks(),
            LinkPredicates.typeEquals(VCloudDirectorMediaType.VDC));
    if (vdc != null) {
        builder.location(findLocationForResource.apply(vdc));
    } else {
        // otherwise, it could be in a public catalog, which is not assigned to a VDC
    }
    builder.ids(from.getHref().toASCIIString()).name(from.getName())
            .supportsImage(ImagePredicates.idEquals(from.getHref().toASCIIString()));
    builder.hypervisor("VMware");
    return builder.build();

}

From source file:org.sonar.cxx.checks.SwitchLastCaseIsDefaultCheck.java

@Override
public void visitNode(AstNode node) {
    List<AstNode> switchCases = getSwitchCases(node);
    int defaultCaseIndex = Iterables.indexOf(switchCases, DEFAULT_CASE_NODE_FILTER);

    if (defaultCaseIndex == -1) {
        getContext().createLineViolation(this, MISSING_DEFAULT_CASE_MESSAGE, node);
    } else {//from ww w  .java  2s  . c  om
        AstNode defaultCase = Iterables.get(switchCases, defaultCaseIndex);

        if (!defaultCase.equals(Iterables.getLast(switchCases))) {
            getContext().createLineViolation(this, DEFAULT_CASE_IS_NOT_LAST_MESSAGE, defaultCase);
        }
    }
}