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

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

Introduction

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

Prototype

public static int size(Iterable<?> iterable) 

Source Link

Document

Returns the number of elements in iterable .

Usage

From source file:com.medvision360.medrecord.spi.tck.LocatableStoreTCKTestBase.java

public void testEHRSupport() throws Exception {
    Iterable<HierObjectID> hierObjectIDs;
    EHR EHR = makeEHR();/*from  w w w  . j  a v a 2s. co m*/

    try {
        store.list(EHR);
        fail("Should not allow listing non-existent EHR");
    } catch (NotFoundException e) {
    }

    HierObjectID uid = new HierObjectID(makeUUID());
    Locatable orig = makeLocatable(uid);

    Locatable inserted = store.insert(EHR, orig);
    assertEqualish(orig, inserted);

    hierObjectIDs = store.list(EHR);
    assertEquals(1, Iterables.size(hierObjectIDs));
    assertEquals(inserted.getUid(), Iterables.getFirst(hierObjectIDs, null));

    hierObjectIDs = store.list(EHR, "COMPOSITION");
    assertEquals(1, Iterables.size(hierObjectIDs));

    hierObjectIDs = store.list(EHR, "PERSON");
    assertEquals(0, Iterables.size(hierObjectIDs));
}

From source file:org.vclipse.vcml.utils.SimplifyingVcmlUtils.java

public Statement mkSimplifiedCompoundStatement(final SimpleStatement... statements) {
    Iterable<SimpleStatement> statementsNonNull = Iterables.filter(Lists.newArrayList(statements),
            Predicates.notNull());//from   w w  w  . j ava  2  s. c  o m
    switch (Iterables.size(statementsNonNull)) {
    case 0:
        return null;
    case 1:
        return Iterables.getFirst(statementsNonNull, null);
    default:
        final CompoundStatement compoundStatement = mkCompoundStatement();
        compoundStatement.getStatements().addAll(Lists.newArrayList(statementsNonNull));
        return compoundStatement;
    }
}

From source file:com.groupon.jenkins.dynamic.build.api.ProcessedBuild.java

@Exported
public Iterable<Map> getAxisList() {

    final Iterable<Combination> layoutList = this.build.getLayouter().list();
    final Iterable<Map> subBuildInfo = Iterables.transform(layoutList, new Function<Combination, Map>() {
        @Override// ww  w .j a  v a2s .  c o m
        public Map apply(@Nullable final Combination combination) {
            final HashMap subBuild = new HashMap();
            subBuild.putAll(combination);
            final hudson.model.Build run = ProcessedBuild.this.build.getRun(combination);
            subBuild.putAll(getSubBuildInfo((DbBackedBuild) run));
            return subBuild;
        }
    });

    final ArrayList<Map> subBuilds = Iterables.size(layoutList) > 1 ? Lists.newArrayList(subBuildInfo)
            : new ArrayList<>();
    subBuilds.add(getMainBuildInfo(this.build));
    return subBuilds;
}

From source file:eu.interedition.collatex.suffixtree.SuffixTree.java

/**
 * Starts Ukkonen's construction algorithm by calling SPA n times, where
 * n is the length of the source string.
 *
 * @param str the source string is a sequence of unsigned characters
 *            (maximum of 256 different symbols). In the original algorithm '$'
 *            was a special character. However,http://www.abc.net.au/news/ in Yona's
 *            version it is appended at the end of the input string and then never used.
 *//*from  w w  w.j  ava 2  s  .  c o m*/
@SuppressWarnings("unchecked")
private SuffixTree(Iterable<T> str, Comparator<T> comparator) {
    this.length = Iterables.size(str) + 1;
    Preconditions.checkArgument(this.length > 1);
    this.source = (T[]) Array.newInstance(Iterables.getFirst(str, null).getClass(), this.length + 1);
    this.comparator = comparator;
    this.virtualEnd = 1; // added to make 1-character suffix trees work

    int i = 0;
    for (T t : str) {
        this.source[++i] = t;
    }
    // the terminal ('$') is never examined but assumed to be there
    this.source[length] = null;

    this.root = new Node(this, null, 0, 0, 0);

    // allocating first node, child of the root (phase 0), the longest
    // path node
    this.root.firstChild = new Node(this, root, 1, length, 1);
}

From source file:org.caleydo.view.domino.internal.FocusOverlay.java

/**
 * @param node/* w  ww . j a  v a2s  . c  om*/
 * @param switcher2
 * @return
 */
private GLElement createButtonBar(String label, GLElementFactorySwitcher s) {
    GLElementContainer c = new GLElementContainer(GLLayouts.flowHorizontal(2));
    c.add(new GLElement(GLRenderers.drawText(label, VAlign.LEFT, new GLPadding(1, 1, 1, 5))));
    final ButtonBarBuilder b = s.createButtonBarBuilder();
    b.layoutAs(EButtonBarLayout.HORIZONTAL).size(24);
    b.prepend(createTransposeButton());
    b.customCallback(this);
    int size = Iterables.size(s) + 1;
    c.add(b.build().setSize(size * 26, -1));
    c.setSize(-1, 24);
    return c;
}

From source file:co.cask.cdap.common.queue.QueueName.java

/**
 * Called from static method {@code QueueName#from(URI)} and {@code QueueName#from(bytes[])}.
 *
 * @param uri of the queue.//from w w w  . jav a2  s  .c o  m
 */
private QueueName(URI uri) {
    this.uri = uri;
    this.stringName = uri.toASCIIString();
    this.byteName = stringName.getBytes(Charsets.US_ASCII);
    Iterable<String> comps = Splitter.on('/').omitEmptyStrings().split(uri.getPath());
    components = new String[Iterables.size(comps)];
    Iterator<String> iter = comps.iterator();
    for (int i = 0; i < components.length; i++) {
        components[i] = iter.next();
    }
}

From source file:com.palantir.common.collect.IterableView.java

public int size() {
    return Iterables.size(delegate());
}

From source file:com.google.devtools.build.lib.rules.java.JavaToolchain.java

private static Artifact getArtifact(String attributeName, RuleContext ruleContext) {
    TransitiveInfoCollection prerequisite = ruleContext.getPrerequisite(attributeName, Mode.HOST);
    if (prerequisite == null) {
        return null;
    }/*ww  w.  j a v  a  2 s  .  c om*/
    Iterable<Artifact> artifacts = prerequisite.getProvider(FileProvider.class).getFilesToBuild();
    if (Iterables.size(artifacts) != 1) {
        ruleContext.attributeError(attributeName, prerequisite.getLabel() + " expected a single artifact");
        return null;
    }
    return Iterables.getOnlyElement(artifacts);
}

From source file:io.brooklyn.ambari.AmbariLiveTestHelper.java

protected void assertAddServiceToClusterEffectorWorks(Application app) {
    final AmbariServer ambariServer = Entities.descendants(app, AmbariServer.class).iterator().next();
    final AmbariAgent ambariAgent = Entities.descendants(app, AmbariAgent.class).iterator().next();
    final Maybe<Effector<?>> effector = EffectorUtils.findEffector(ambariServer.getEntityType().getEffectors(),
            "addServiceToCluster");
    if (effector.isAbsentOrNull()) {
        throw new IllegalStateException("Cannot get the addServiceToCluster effector");
    }/*w  w  w  . ja  v  a 2  s  .com*/

    final Task<?> effectorTask = ambariServer.invoke(effector.get(),
            ImmutableMap.of("cluster", "Cluster1", "service", "FLUME", "mappings",
                    ImmutableMap.of("FLUME_HANDLER", ambariAgent.getFqdn()), "configuration",
                    ImmutableMap.of("flume-env",
                            ImmutableMap.of("flume_conf_dir", "/etc/flume/conf", "flume_log_dir",
                                    "/var/log/flume", "flume_run_dir", "/var/run/flume", "flume_user",
                                    "flume"))));

    effectorTask.getUnchecked();
    assertFalse(effectorTask.isError(), "Effector should not fail");
    assertEquals(2, Iterables.size(Tasks.children(effectorTask)));
    assertFalse(Tasks.failed(Tasks.children(effectorTask)).iterator().hasNext(),
            "All sub-task should not fail");
}

From source file:co.cask.cdap.examples.sparkpagerank.SparkPageRankProgram.java

@Override
public void run(SparkContext sc) {
    LOG.info("Processing backlinkURLs data");
    JavaPairRDD<LongWritable, Text> backlinkURLs = sc.readFromStream("backlinkURLStream", Text.class);
    int iterationCount = getIterationCount(sc);

    LOG.info("Grouping data by key");
    // Grouping backlinks by unique URL in key
    JavaPairRDD<String, Iterable<String>> links = backlinkURLs.values()
            .mapToPair(new PairFunction<Text, String, String>() {
                @Override/*from  w ww .  j a v a2  s  .  c  o  m*/
                public Tuple2<String, String> call(Text s) {
                    String[] parts = SPACES.split(s.toString());
                    return new Tuple2<>(parts[0], parts[1]);
                }
            }).distinct().groupByKey().cache();

    // Initialize default rank for each key URL
    JavaPairRDD<String, Double> ranks = links.mapValues(new Function<Iterable<String>, Double>() {
        @Override
        public Double call(Iterable<String> rs) {
            return 1.0;
        }
    });
    // Calculates and updates URL ranks continuously using PageRank algorithm.
    for (int current = 0; current < iterationCount; current++) {
        LOG.debug("Processing data with PageRank algorithm. Iteration {}/{}", current + 1, (iterationCount));
        // Calculates URL contributions to the rank of other URLs.
        JavaPairRDD<String, Double> contribs = links.join(ranks).values()
                .flatMapToPair(new PairFlatMapFunction<Tuple2<Iterable<String>, Double>, String, Double>() {
                    @Override
                    public Iterable<Tuple2<String, Double>> call(Tuple2<Iterable<String>, Double> s) {
                        LOG.debug("Processing {} with rank {}", s._1(), s._2());
                        int urlCount = Iterables.size(s._1());
                        List<Tuple2<String, Double>> results = new ArrayList<>();
                        for (String n : s._1()) {
                            results.add(new Tuple2<>(n, s._2() / urlCount));
                        }
                        return results;
                    }
                });
        // Re-calculates URL ranks based on backlink contributions.
        ranks = contribs.reduceByKey(new Sum()).mapValues(new Function<Double, Double>() {
            @Override
            public Double call(Double sum) {
                return 0.15 + sum * 0.85;
            }
        });
    }

    LOG.info("Writing ranks data");

    final ServiceDiscoverer discoveryServiceContext = sc.getServiceDiscoverer();
    final Metrics sparkMetrics = sc.getMetrics();
    JavaPairRDD<byte[], Integer> ranksRaw = ranks
            .mapToPair(new PairFunction<Tuple2<String, Double>, byte[], Integer>() {
                @Override
                public Tuple2<byte[], Integer> call(Tuple2<String, Double> tuple) throws Exception {
                    LOG.debug("URL {} has rank {}", Arrays.toString(tuple._1().getBytes(Charsets.UTF_8)),
                            tuple._2());
                    URL serviceURL = discoveryServiceContext
                            .getServiceURL(SparkPageRankApp.GOOGLE_TYPE_PR_SERVICE_NAME);
                    if (serviceURL == null) {
                        throw new RuntimeException(
                                "Failed to discover service: " + SparkPageRankApp.GOOGLE_TYPE_PR_SERVICE_NAME);
                    }
                    try {
                        URLConnection connection = new URL(serviceURL,
                                String.format("transform/%s", tuple._2().toString())).openConnection();
                        try (BufferedReader reader = new BufferedReader(
                                new InputStreamReader(connection.getInputStream(), Charsets.UTF_8))) {
                            String pr = reader.readLine();
                            if ((Integer.parseInt(pr)) == POPULAR_PAGE_THRESHOLD) {
                                sparkMetrics.count(POPULAR_PAGES, 1);
                            } else if (Integer.parseInt(pr) <= UNPOPULAR_PAGE_THRESHOLD) {
                                sparkMetrics.count(UNPOPULAR_PAGES, 1);
                            } else {
                                sparkMetrics.count(REGULAR_PAGES, 1);
                            }
                            return new Tuple2(tuple._1().getBytes(Charsets.UTF_8), Integer.parseInt(pr));
                        }
                    } catch (Exception e) {
                        LOG.warn("Failed to read the Stream for service {}",
                                SparkPageRankApp.GOOGLE_TYPE_PR_SERVICE_NAME, e);
                        throw Throwables.propagate(e);
                    }
                }
            });

    // Store calculated results in output Dataset.
    // All calculated results are stored in one row.
    // Each result, the calculated URL rank based on backlink contributions, is an entry of the row.
    // The value of the entry is the URL rank.
    sc.writeToDataset(ranksRaw, "ranks", byte[].class, Integer.class);

    LOG.info("PageRanks successfuly computed and written to \"ranks\" dataset");
}