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

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

Introduction

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

Prototype

public static int size(Iterator<?> iterator) 

Source Link

Document

Returns the number of elements remaining in iterator .

Usage

From source file:org.janusgraph.graphdb.serializer.SerializerGraphConfiguration.java

@Test
public void testOnlyRegisteredSerialization() {
    JanusGraphManagement mgmt = graph.openManagement();
    PropertyKey time = mgmt.makePropertyKey("time").dataType(Integer.class).make();
    PropertyKey any = mgmt.makePropertyKey("any").cardinality(Cardinality.LIST).dataType(Object.class).make();
    mgmt.buildIndex("byTime", Vertex.class).addKey(time).buildCompositeIndex();
    EdgeLabel knows = mgmt.makeEdgeLabel("knows").make();
    VertexLabel person = mgmt.makeVertexLabel("person").make();
    mgmt.commit();//  www . j ava 2  s .co m

    JanusGraphTransaction tx = graph.newTransaction();
    JanusGraphVertex v = tx.addVertex("person");
    v.property("time", 5);
    v.property("any", new Double(5.0));
    v.property("any", new TClass1(5, 1.5f));
    v.property("any", TEnum.THREE);
    tx.commit();

    tx = graph.newTransaction();
    v = (JanusGraphVertex) tx.query().has("time", 5).vertices().iterator().next();
    assertEquals(5, (int) v.value("time"));
    assertEquals(3, Iterators.size(v.properties("any")));
    tx.rollback();

    //Verify that non-registered objects aren't allowed
    for (Object o : new Object[] { new TClass2("abc", 5) }) {
        tx = graph.newTransaction();
        v = tx.addVertex("person");
        try {
            v.property("any", o); //Should not be allowed
            tx.commit();
            fail();
        } catch (IllegalArgumentException e) {
        } finally {
            if (tx.isOpen())
                tx.rollback();
        }

    }
}

From source file:qdg.contrib.ClosenessCentrality.java

private int ensureNumOfNodes() {
    if (numOfNodes == null) {
        numOfNodes = Iterators.size(g.getNodeIterator());
    }
    return numOfNodes;
}

From source file:net.slashies.phpBridge.AbstractLongMap.java

@Override
public int size() {
    return Iterators.size(entryIterator());
}

From source file:org.polymap.core.data.feature.recordstore.RFeatureCollection.java

public int size() {
    return size.get(new Supplier<Integer>() {
        public Integer get() {
            try {
                PostProcessResultSet results = queryDialect.getFeatureStates(fs, query);
                return results.hasPostProcessing() ? Iterators.size(results.iterator()) : results.size();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }//from   w  w w  .  j  ava2 s.c  o  m
        }
    });
}

From source file:io.scigraph.owlapi.postprocessors.Clique.java

@Override
public void run() {
    logger.info("Starting clique merge");
    GlobalGraphOperations globalGraphOperations = GlobalGraphOperations.at(graphDb);

    Transaction tx = graphDb.beginTx();/*from   w w  w .j a  va2s . c  o  m*/
    ResourceIterable<Node> allNodes = globalGraphOperations.getAllNodes();
    int size = Iterators.size(allNodes.iterator());
    tx.success();
    tx.close();

    logger.info(size + " nodes left to process");

    tx = graphDb.beginTx();
    TraversalDescription traversalDescription = graphDb.traversalDescription().breadthFirst()
            .uniqueness(Uniqueness.NODE_GLOBAL);
    for (RelationshipType rel : relationships) {
        traversalDescription = traversalDescription.relationships(rel, Direction.BOTH);
    }

    Set<Long> processedNodes = new HashSet<Long>();

    for (Node baseNode : allNodes) {

        size -= 1;

        if (size % 100000 == 0) {
            logger.info(size + " nodes left to process");
        }

        if (size % 10000 == 0) {
            logger.fine("Node batch commit");
            tx.success();
            tx.close();
            tx = graphDb.beginTx();
        }

        logger.fine("Processing Node - " + baseNode.getProperty(NodeProperties.IRI));

        if (!processedNodes.contains(baseNode.getId())) {
            // Keep a list of equivalentNodes
            List<Node> clique = new ArrayList<Node>();
            for (Node node : traversalDescription.traverse(baseNode).nodes()) {
                logger.fine("-- " + node.getProperty(NodeProperties.IRI));
                clique.add(node);
                processedNodes.add(node.getId());
            }

            logger.fine("clique size: " + clique.size());
            if (clique.size() == 1) {
                Node defactoLeader = clique.get(0);
                markAsCliqueLeader(defactoLeader);
            } else {
                Node leader = electCliqueLeader(clique, prefixLeaderPriority);
                markAsCliqueLeader(leader);
                clique.remove(leader); // keep only the peasants
                moveEdgesToLeader(leader, clique, tx);
                ensureLabel(leader, clique);
            }

        }

    }

    tx.success();
    tx.close();
}

From source file:org.geogit.api.porcelain.ResetOp.java

/**
 * Executes the reset operation.//  w  w  w  .  j  av  a  2 s  .co m
 * 
 * @return always {@code true}
 */
@Override
public Boolean call() {
    Preconditions.checkState(!(patterns.size() > 0 && mode != ResetMode.NONE),
            "Ambiguous call, cannot specify paths and reset mode.");

    final Optional<Ref> currHead = command(RefParse.class).setName(Ref.HEAD).call();
    Preconditions.checkState(currHead.isPresent(), "Repository has no HEAD, can't reset.");
    Preconditions.checkState(currHead.get() instanceof SymRef, "Can't reset from detached HEAD");
    final SymRef headRef = (SymRef) currHead.get();

    final String currentBranch = headRef.getTarget();

    if (commit == null) {
        commit = Suppliers.ofInstance(currHead.get().getObjectId());
    }

    Preconditions.checkState(!ObjectId.NULL.equals(commit.get()), "Commit could not be resolved.");

    RevCommit oldCommit = repository.getCommit(commit.get());

    if (patterns.size() > 0) {
        for (String pattern : patterns) {
            DiffTree diffOp = command(DiffTree.class).setOldTree(repository.getIndex().getTree().getId())
                    .setNewTree(oldCommit.getTreeId()).setFilterPath(pattern);

            Iterator<DiffEntry> diff = diffOp.call();

            final long numChanges = Iterators.size(diffOp.call());

            repository.getIndex().stage(subProgress((1.f / patterns.size()) * 100.f), diff, numChanges);
        }
    } else {
        if (mode == ResetMode.NONE) {
            mode = ResetMode.MIXED;
        }
        switch (mode) {
        case HARD:
            // Update the index and the working tree to the target tree
            getIndex().updateStageHead(oldCommit.getTreeId());
            getWorkTree().updateWorkHead(oldCommit.getTreeId());
            break;
        case SOFT:
            // Do not update index or working tree to the target tree
            break;
        case MIXED:
            // Only update the index to the target tree
            getIndex().updateStageHead(oldCommit.getTreeId());
            break;
        default:
            throw new UnsupportedOperationException("Unsupported reset mode.");
        }

        // Update branch head to the specified commit
        command(UpdateRef.class).setName(currentBranch).setNewValue(oldCommit.getId()).call();
        command(UpdateSymRef.class).setName(Ref.HEAD).setNewValue(currentBranch).call();

        Optional<Ref> ref = command(RefParse.class).setName(Ref.MERGE_HEAD).call();
        if (ref.isPresent()) {
            command(UpdateRef.class).setName(Ref.MERGE_HEAD).setDelete(true).call();
        }
    }
    return true;
}

From source file:com.continuuity.loom.scheduler.task.TaskQueueService.java

@Inject
private TaskQueueService(@Named(Constants.Queue.PROVISIONER) final QueueGroup taskQueues,
        @Named(Constants.Queue.JOB) QueueGroup jobQueues, ClusterStoreService clusterStoreService,
        TenantProvisionerService tenantProvisionerService, TaskService taskService, NodeService nodeService,
        TenantStore tenantStore, Configuration conf, LoomStats loomStats) {
    this.clusterStore = clusterStoreService.getSystemView();
    this.taskService = taskService;
    this.nodeService = nodeService;
    this.tenantProvisionerService = tenantProvisionerService;
    this.loomStats = loomStats;
    this.taskQueues = taskQueues;
    this.jobQueues = jobQueues;
    this.tenantStore = tenantStore;
    final int queueCacheSeconds = conf.getInt(Constants.Metrics.QUEUE_CACHE_SECONDS);
    // queue metrics can be expensive to fetch
    this.queueMetricsCache = CacheBuilder.newBuilder().expireAfterWrite(queueCacheSeconds, TimeUnit.SECONDS)
            .build(new CacheLoader<String, QueueMetrics>() {
                @Override/*from  w  w w. ja v a2s  .co m*/
                public QueueMetrics load(String tenantId) {
                    int numQueued = Iterators.size(taskQueues.getQueued(tenantId));
                    int numInProgress = Iterators.size(taskQueues.getBeingConsumed(tenantId));
                    return new QueueMetrics(numQueued, numInProgress);
                }
            });
}

From source file:sg.atom.utils.datastructure.parser.DelimitedParser.java

@Override
public Map<String, Object> parse(String input) throws FormattedException {
    try {/*from   w w w .  j a v a2  s.c  o m*/
        Iterable<String> values = splitter.split(input);

        if (fieldNames == null) {
            setFieldNames(ParserUtils.generateFieldNames(Iterators.size(values.iterator())));
        }

        return Utils.zipMapPartial(fieldNames, Iterables.transform(values, valueFunction));
    } catch (Exception e) {
        Throwables.propagateIfInstanceOf(e, FormattedException.class);
        throw new FormattedException.Builder().withErrorCode(FormattedException.ErrorCode.UNPARSABLE_ROW)
                .withMessage(e.getMessage()).build();
    }
}

From source file:org.locationtech.geogig.api.porcelain.ResetOp.java

/**
 * Executes the reset operation./*from w ww . j  av a 2  s.c  o  m*/
 * 
 * @return always {@code true}
 */
@Override
protected Boolean _call() {
    Preconditions.checkState(!(patterns.size() > 0 && mode != ResetMode.NONE),
            "Ambiguous call, cannot specify paths and reset mode.");

    final Optional<Ref> currHead = command(RefParse.class).setName(Ref.HEAD).call();
    Preconditions.checkState(currHead.isPresent(), "Repository has no HEAD, can't reset.");
    Preconditions.checkState(currHead.get() instanceof SymRef, "Can't reset from detached HEAD");
    final SymRef headRef = (SymRef) currHead.get();

    final String currentBranch = headRef.getTarget();

    if (commit == null) {
        commit = Suppliers.ofInstance(currHead.get().getObjectId());
    }

    Preconditions.checkState(!ObjectId.NULL.equals(commit.get()), "Commit could not be resolved.");

    Repository repository = repository();
    RevCommit oldCommit = repository.getCommit(commit.get());

    if (patterns.size() > 0) {
        for (String pattern : patterns) {
            DiffTree diffOp = command(DiffTree.class).setOldTree(repository.index().getTree().getId())
                    .setNewTree(oldCommit.getTreeId()).setPathFilter(pattern);

            Iterator<DiffEntry> diff = diffOp.call();

            final long numChanges = Iterators.size(diffOp.call());
            if (numChanges == 0) {
                // We are reseting to the current version, so there is nothing to do. However,
                // if we are in a conflict state, the conflict should be removed and calling
                // stage() will not do it, so we do it here
                conflictsDatabase().removeConflict(null, pattern);
            } else {
                repository.index().stage(subProgress((1.f / patterns.size()) * 100.f), diff, numChanges);
            }
        }
    } else {
        if (mode == ResetMode.NONE) {
            mode = ResetMode.MIXED;
        }
        switch (mode) {
        case HARD:
            // Update the index and the working tree to the target tree
            index().updateStageHead(oldCommit.getTreeId());
            workingTree().updateWorkHead(oldCommit.getTreeId());
            break;
        case SOFT:
            // Do not update index or working tree to the target tree
            break;
        case MIXED:
            // Only update the index to the target tree
            index().updateStageHead(oldCommit.getTreeId());
            break;
        default:
            throw new UnsupportedOperationException("Unsupported reset mode.");
        }

        // Update branch head to the specified commit
        command(UpdateRef.class).setName(currentBranch).setNewValue(oldCommit.getId()).call();
        command(UpdateSymRef.class).setName(Ref.HEAD).setNewValue(currentBranch).call();

        Optional<Ref> ref = command(RefParse.class).setName(Ref.MERGE_HEAD).call();
        if (ref.isPresent()) {
            command(UpdateRef.class).setName(Ref.MERGE_HEAD).setDelete(true).call();
        }
    }
    return true;
}

From source file:org.apache.james.queue.rabbitmq.view.cassandra.CassandraMailQueueView.java

@Override
public long getSize() {
    return Iterators.size(browse());
}