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.eucalyptus.compute.common.internal.tags.TagSupport.java

/**
 * Get the tags for the given resources, grouped by ID and ordered for display.
 * /*  w  w w  .  j  a va2s  .c  o  m*/
 * @param owner The account for the tags
 * @param identifiers The resource identifiers for the tags
 * @return The tag map with an entry for each requested resource
 */
public Map<String, List<Tag>> getResourceTagMap(final OwnerFullName owner, final Iterable<String> identifiers) {
    final int identifiersSize = Iterables.size(identifiers);
    final Map<String, List<Tag>> tagMap = Maps.newHashMapWithExpectedSize(identifiersSize);
    for (final String id : identifiers) {
        tagMap.put(id, Lists.<Tag>newArrayList());
    }
    if (!tagMap.isEmpty()) {
        final Tag example = example(owner);
        final Criterion idRestriction = identifiersSize < 1000 ? Property.forName(tagClassResourceField)
                .in(DetachedCriteria.forClass(resourceClass)
                        .add(Restrictions.in(resourceClassIdField, Lists.newArrayList(identifiers)))
                        .setProjection(Projections.id()))
                : Restrictions.conjunction();
        try {
            final List<Tag> tags = Tags.list(example, Predicates.alwaysTrue(), idRestriction,
                    Collections.<String, String>emptyMap());
            for (final Tag tag : tags) {
                final List<Tag> keyTags = tagMap.get(tag.getResourceId());
                if (keyTags != null) {
                    keyTags.add(tag);
                }
            }
        } catch (Exception e) {
            log.error(e, e);
        }
        Ordering<Tag> order = Ordering.natural().onResultOf(Tags.key());
        for (final String id : identifiers) {
            Collections.sort(tagMap.get(id), order);
        }
    }
    return tagMap;
}

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

@Override
public ConfiguredTarget create(RuleContext ruleContext) throws RuleErrorException, InterruptedException {
    NestedSet<Artifact> filesToBuild = NestedSetBuilder.wrap(Order.STABLE_ORDER,
            ruleContext.getOutputArtifacts());
    NestedSetBuilder<Artifact> resolvedSrcsBuilder = NestedSetBuilder.stableOrder();

    if (filesToBuild.isEmpty()) {
        ruleContext.attributeError("outs", "Genrules without outputs don't make sense");
    }/*from   w ww  .  jav a 2s .c om*/
    if (ruleContext.attributes().get("executable", Type.BOOLEAN) && Iterables.size(filesToBuild) > 1) {
        ruleContext.attributeError("executable",
                "if genrules produce executables, they are allowed only one output. "
                        + "If you need the executable=1 argument, then you should split this genrule into "
                        + "genrules producing single outputs");
    }

    ImmutableMap.Builder<Label, NestedSet<Artifact>> labelMap = ImmutableMap.builder();
    for (TransitiveInfoCollection dep : ruleContext.getPrerequisites("srcs", Mode.TARGET)) {
        // This target provides specific types of files for genrules.
        GenRuleSourcesProvider provider = dep.getProvider(GenRuleSourcesProvider.class);
        NestedSet<Artifact> files = (provider != null) ? provider.getGenruleFiles()
                : dep.getProvider(FileProvider.class).getFilesToBuild();
        resolvedSrcsBuilder.addTransitive(files);
        labelMap.put(AliasProvider.getDependencyLabel(dep), files);
    }
    NestedSet<Artifact> resolvedSrcs = resolvedSrcsBuilder.build();

    CommandHelper commandHelper = new CommandHelper(ruleContext,
            ruleContext.getPrerequisites("tools", Mode.HOST), labelMap.build());

    if (ruleContext.hasErrors()) {
        return null;
    }

    String baseCommand = commandHelper.resolveCommandAndExpandLabels(
            ruleContext.attributes().get("heuristic_label_expansion", Type.BOOLEAN), false);

    // Adds the genrule environment setup script before the actual shell command
    String command = String.format("source %s; %s",
            ruleContext.getPrerequisiteArtifact("$genrule_setup", Mode.HOST).getExecPath(), baseCommand);

    command = resolveCommand(command, ruleContext, resolvedSrcs, filesToBuild);

    String message = ruleContext.attributes().get("message", Type.STRING);
    if (message.isEmpty()) {
        message = "Executing genrule";
    }

    ImmutableMap<String, String> env = ruleContext.getConfiguration().getLocalShellEnvironment();
    ImmutableSet<String> clientEnvVars = ruleContext.getConfiguration().getVariableShellEnvironment();

    Map<String, String> executionInfo = Maps.newLinkedHashMap();
    executionInfo.putAll(TargetUtils.getExecutionInfo(ruleContext.getRule()));

    if (ruleContext.attributes().get("local", Type.BOOLEAN)) {
        executionInfo.put("local", "");
    }

    executionInfo.putAll(getExtraExecutionInfo(ruleContext, baseCommand));

    NestedSetBuilder<Artifact> inputs = NestedSetBuilder.stableOrder();
    inputs.addAll(resolvedSrcs);
    inputs.addAll(commandHelper.getResolvedTools());
    FilesToRunProvider genruleSetup = ruleContext.getPrerequisite("$genrule_setup", Mode.HOST,
            FilesToRunProvider.class);
    inputs.addAll(genruleSetup.getFilesToRun());
    List<String> argv = commandHelper.buildCommandLine(command, inputs, ".genrule_script.sh",
            ImmutableMap.copyOf(executionInfo));

    // TODO(bazel-team): Make the make variable expander pass back a list of these.
    if (requiresCrosstool(baseCommand)) {
        // If cc is used, silently throw in the crosstool filegroup as a dependency.
        inputs.addTransitive(CppHelper.getToolchain(ruleContext, ":cc_toolchain").getCrosstoolMiddleman());
    }
    if (requiresJdk(baseCommand)) {
        // If javac is used, silently throw in the jdk filegroup as a dependency.
        // Note we expand Java-related variables with the *host* configuration.
        inputs.addTransitive(JavaHelper.getHostJavabaseInputs(ruleContext));
    }

    for (NestedSet<Artifact> extraInputs : getExtraInputArtifacts(ruleContext, baseCommand)) {
        inputs.addTransitive(extraInputs);
    }

    if (isStampingEnabled(ruleContext)) {
        inputs.add(ruleContext.getAnalysisEnvironment().getStableWorkspaceStatusArtifact());
        inputs.add(ruleContext.getAnalysisEnvironment().getVolatileWorkspaceStatusArtifact());
    }

    ruleContext.registerAction(new GenRuleAction(ruleContext.getActionOwner(),
            ImmutableList.copyOf(commandHelper.getResolvedTools()), inputs.build(), filesToBuild, argv, env,
            clientEnvVars, ImmutableMap.copyOf(executionInfo),
            new CompositeRunfilesSupplier(commandHelper.getToolsRunfilesSuppliers()),
            message + ' ' + ruleContext.getLabel()));

    RunfilesProvider runfilesProvider = RunfilesProvider.withData(
            // No runfiles provided if not a data dependency.
            Runfiles.EMPTY,
            // We only need to consider the outputs of a genrule
            // No need to visit the dependencies of a genrule. They cross from the target into the host
            // configuration, because the dependencies of a genrule are always built for the host
            // configuration.
            new Runfiles.Builder(ruleContext.getWorkspaceName(),
                    ruleContext.getConfiguration().legacyExternalRunfiles())
                            .addTransitiveArtifacts(filesToBuild).build());

    RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext)
            .setFilesToBuild(filesToBuild).setRunfilesSupport(null, getExecutable(ruleContext, filesToBuild))
            .addProvider(RunfilesProvider.class, runfilesProvider);

    builder = updateBuilder(builder, ruleContext, filesToBuild);
    return builder.build();
}

From source file:com.spectralogic.ds3client.helpers.strategy.transferstrategy.AbstractTransferStrategy.java

/**
 * Perform data movement according to the properties you specify in {@link TransferStrategyBuilder}.
 * @throws IOException/*  w w w  .j a v a2s . c  om*/
 */
@Override
public void transfer() throws IOException {
    cachedException.set(null);

    final AtomicInteger numBlobsRemaining = new AtomicInteger(jobState.numBlobsInJob());

    while (!Thread.currentThread().isInterrupted() && numBlobsRemaining.get() > 0) {
        try {
            final Iterable<JobPart> jobParts = jobPartsNotAlreadyTransferred();

            final int numJobParts = Iterables.size(jobParts);

            if (numJobParts <= 0) {
                break;
            }

            final CountDownLatch countDownLatch = new CountDownLatch(numJobParts);
            transferJobParts(jobParts, countDownLatch, numBlobsRemaining);
            countDownLatch.await();
        } catch (final Ds3NoMoreRetriesException | FailedRequestException e) {
            emitFailureEvent(makeFailureEvent(failureActivity, e, firstChunk()));
            throw e;
        } catch (final InterruptedException | NoSuchElementException e) {
            Thread.currentThread().interrupt();
        } catch (final Throwable t) {
            emitFailureAndSetCachedException(t);
        }
    }

    if (cachedException.get() != null) {
        throw cachedException.get();
    }
}

From source file:org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.BaseDispatcherParser.java

/**
 * can return null only if you override ParsingStrategy and explicitely return null
 * @param elements elements to be parsed into NormalizedNode
 * @param schema schema belonging to the type N of NormalizedNode
 * @return child of DataContainerNode as a result of parsing list of E elements with schema S
 *//*from   w  w w. j  a v a  2 s.c  o  m*/
@Nullable
@Override
public N parse(final Iterable<E> elements, final S schema) {

    checkAtLeastOneNode(schema, elements);

    DataContainerNodeBuilder<P, N> containerBuilder = getBuilder(schema);

    // Map child nodes to QName
    LinkedListMultimap<QName, E> mappedChildElements = mapChildElements(elements);

    // Map child nodes from Augments
    Map<QName, AugmentationSchema> mappedAugmentChildNodes = mapChildElementsFromAugments(schema);
    LinkedListMultimap<AugmentationSchema, E> augmentsToElements = LinkedListMultimap.create();

    // Map child nodes from choices
    Map<QName, ChoiceSchemaNode> mappedChoiceChildNodes = mapChildElementsFromChoices(schema);
    LinkedListMultimap<ChoiceSchemaNode, E> choicesToElements = LinkedListMultimap.create();

    Map<QName, String> attributes = getAttributes(elements.iterator().next());
    if (containerBuilder instanceof AttributesBuilder) {
        final int size = Iterables.size(elements);
        Preconditions.checkArgument(size == 1, "Unexpected number of elements: %s, should be 1 for: %s", size,
                schema);
        ((AttributesBuilder<?>) containerBuilder).withAttributes(attributes);
    }

    //parse keys first
    if (schema instanceof ListSchemaNode) {
        for (QName qname : ((ListSchemaNode) schema).getKeyDefinition()) {
            final QName noRev = qname.withoutRevision();
            if (mappedChildElements.get(noRev).isEmpty()) {
                continue;
            }

            DataSchemaNode childSchema = getSchemaForChild(schema, qname);
            List<E> childrenForQName = mappedChildElements.removeAll(noRev);

            DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> optionalChildNode = getDispatcher()
                    .dispatchChildElement(childSchema, childrenForQName);
            if (optionalChildNode != null) {
                containerBuilder.withChild(optionalChildNode);
            }
        }
    }

    //stage attribues for strategy before going deeper in the recursion
    buildingStrategy.prepareAttributes(attributes, containerBuilder);

    // process Child nodes
    for (QName childPartialQName : mappedChildElements.keySet()) {
        DataSchemaNode childSchema = getSchemaForChild(schema, childPartialQName);
        //with strict parsing an exception would be already thrown, with nonstrict we want to ignore this node
        if (childSchema == null) {
            continue;
        }
        List<E> childrenForQName = mappedChildElements.get(childPartialQName);

        // Augment
        if (isMarkedAs(mappedAugmentChildNodes, childSchema.getQName())) {
            AugmentationSchema augmentationSchema = mappedAugmentChildNodes.get(childSchema.getQName());
            augmentsToElements.putAll(augmentationSchema, childrenForQName);
            // Choices
        } else if (isMarkedAs(mappedChoiceChildNodes, childSchema.getQName())) {
            ChoiceSchemaNode choiceSchema = mappedChoiceChildNodes.get(childSchema.getQName());
            choicesToElements.putAll(choiceSchema, childrenForQName);
            // Regular child nodes
        } else {
            DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> optionalChildNode = getDispatcher()
                    .dispatchChildElement(childSchema, childrenForQName);
            if (optionalChildNode != null) {
                containerBuilder.withChild(optionalChildNode);
            }
        }
    }

    // TODO ordering is not preserved for choice and augment elements
    for (ChoiceSchemaNode choiceSchema : choicesToElements.keySet()) {
        DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> optionalChild = getDispatcher()
                .dispatchChildElement(choiceSchema, choicesToElements.get(choiceSchema));
        if (optionalChild != null) {
            containerBuilder.withChild(optionalChild);
        }
    }

    for (AugmentationSchema augmentSchema : augmentsToElements.keySet()) {
        Set<DataSchemaNode> realChildSchemas = getRealSchemasForAugment(schema, augmentSchema);
        EffectiveAugmentationSchema augSchemaProxy = new EffectiveAugmentationSchema(augmentSchema,
                realChildSchemas);
        DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> optionalChild = getDispatcher()
                .dispatchChildElement(augSchemaProxy, augmentsToElements.get(augmentSchema));
        if (optionalChild != null) {
            containerBuilder.withChild(optionalChild);
        }
    }

    return buildingStrategy.build(containerBuilder);
}

From source file:org.locationtech.geogig.storage.memory.HeapGraphDatabase.java

@Override
public int getDepth(ObjectId commitId) {
    Preconditions.checkNotNull(commitId);
    Optional<Node> nodeOpt = graph.get(commitId);
    Preconditions.checkArgument(nodeOpt.isPresent(), "No graph entry for commit %s on %s", commitId,
            this.toString());
    Node node = nodeOpt.get();/*w  ww.ja v  a 2s.  co  m*/
    PathToRootWalker walker = new PathToRootWalker(node);
    int depth = 0;
    O: while (walker.hasNext()) {
        for (Node n : walker.next()) {
            if (Iterables.size(n.to()) == 0) {
                break O;
            }
        }
        depth++;
    }
    return depth;
}

From source file:org.apache.giraph.partition.PartitionPhilosophersTable.java

/**
 * Constructor/*from  ww  w .ja  v a  2  s .c  om*/
 *
 * @param conf Configuration used.
 * @param serviceWorker Service worker
 */
public PartitionPhilosophersTable(ImmutableClassesGiraphConfiguration<I, V, E> conf,
        CentralizedServiceWorker<I, V, E> serviceWorker) {
    this.conf = conf;
    this.serviceWorker = serviceWorker;

    int numLocalPartitions = serviceWorker.getPartitionStore().getNumPartitions();

    // need one entry for every local partition
    this.pMap = new Int2ObjectOpenHashMap<Int2ByteOpenHashMap>(numLocalPartitions);

    this.pHungry = new IntOpenHashSet(Math.min(conf.getNumComputeThreads(), numLocalPartitions));
    this.pEating = new IntOpenHashSet(Math.min(conf.getNumComputeThreads(), numLocalPartitions));

    // this gives total number of partitions, b/c WorkerGraphPartitioner
    // must store location of ALL partitions in system
    // (PartitionOwners are init and assigned by master)
    this.numTotalPartitions = Iterables.size(serviceWorker.getPartitionOwners());

    this.taskIdMap = new Int2IntOpenHashMap(numTotalPartitions);
    this.allHaltedMap = new Int2BooleanOpenHashMap(numLocalPartitions);

    this.waitAllRunnable = new Runnable() {
        @Override
        public void run() {
            PartitionPhilosophersTable.this.serviceWorker.getWorkerClient().waitAllRequests();
        }
    };

    //LOG.info("[[PTABLE]] ========================================");
    //LOG.info("[[PTABLE]] I am worker: " +
    //         serviceWorker.getWorkerInfo().getTaskId());
}

From source file:org.eclipse.osee.orcs.core.internal.search.CallableQueryFactory.java

public CancellableCallable<ResultSet<Match<ArtifactReadable, AttributeReadable<?>>>> createSearchWithMatches(
        OrcsSession session, QueryData queryData) {
    return new AbstractSearchCallable<ResultSet<Match<ArtifactReadable, AttributeReadable<?>>>>(session,
            queryData) {// ww w . j a v  a2s . c  o m

        @Override
        protected ResultSet<Match<ArtifactReadable, AttributeReadable<?>>> innerCall() throws Exception {
            GraphBuilder handler = builderFactory.createGraphBuilder(provider);
            ArtifactMatchDataHandler matchHandler = new ArtifactMatchDataHandler(getSession(), handler,
                    proxyManager);
            OptionsUtil.setLoadLevel(getQueryData().getOptions(), LoadLevel.ALL);
            queryEngine.createArtifactQuery(getSession(), getQueryData(), matchHandler).call();
            List<Match<ArtifactReadable, AttributeReadable<?>>> results = matchHandler.getResults();
            setItemsFound(Iterables.size(results));
            return ResultSets.newResultSet(results);
        }
    };
}

From source file:org.eclipse.xtext.ui.editor.model.edit.DefaultTextEditComposer.java

protected List<TextEdit> getObjectEdits() {
    final Collection<EObject> modifiedObjects = getModifiedObjects();
    Collection<EObject> topLevelObjects = EcoreUtil.filterDescendants(modifiedObjects);
    Iterable<EObject> containedModifiedObjects = Collections.emptyList();
    if (!resource.getContents().isEmpty()) {
        final EObject root = resource.getContents().get(0);
        containedModifiedObjects = Iterables.filter(topLevelObjects, new Predicate<EObject>() {
            @Override/*from  ww  w.  ja va  2 s .com*/
            public boolean apply(EObject input) {
                return EcoreUtil.isAncestor(root, input);
            }
        });
    }
    List<TextEdit> edits = Lists.newArrayListWithExpectedSize(Iterables.size(containedModifiedObjects));
    for (EObject modifiedObject : containedModifiedObjects) {
        ReplaceRegion replaceRegion = serializer.serializeReplacement(modifiedObject, getSaveOptions());
        TextEdit edit = new ReplaceEdit(replaceRegion.getOffset(), replaceRegion.getLength(),
                replaceRegion.getText());
        edits.add(edit);
    }
    return edits;
}

From source file:org.opendaylight.openflowplugin.impl.util.GroupUtil.java

public static <O> Function<List<RpcResult<O>>, RpcResult<List<BatchFailedGroupsOutput>>> createCumulatingFunction(
        final Iterable<? extends org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group> inputBatchGroups) {
    return createCumulatingFunction(inputBatchGroups, Iterables.size(inputBatchGroups));
}

From source file:edu.udo.scaffoldhunter.gui.SubsetActions.java

/**
 * Updates the subset actions' context./*www  .  j  ava  2s .  co  m*/
 * 
 * @param subset
 *            the subset the actions refer to
 * @param selectedSubsets
 *            all selected subsets, may be null
 * @param view
 *            the active view
 */
public void updateContext(Subset subset, Iterable<Subset> selectedSubsets, View view) {
    if (selectedSubsets == null) {
        List<Subset> l = Lists.newArrayList();
        l.add(subset);
        selectedSubsets = l;
    }

    this.subset = subset;
    this.selectedSubsets = selectedSubsets;

    showInCurrentView.setEnabled(subset != null && view != null);

    Icon icon = view != null ? ViewClassRegistry.getClassIcon(view.getClass()) : null;
    showInCurrentView.putValue(Action.SMALL_ICON, icon);

    addToSelection.setEnabled(subset != null);
    removeFromSelection.setEnabled(subset != null);
    replaceSelection.setEnabled(subset != null);
    filter.setEnabled(subset != null);
    rename.setEnabled(subset != null);
    editComment.setEnabled(subset != null);
    export.setEnabled(subset != null);
    subsetFromRing.setEnabled(subset != null);

    // can't delete the root subset
    delete.setEnabled(!Iterables.contains(selectedSubsets, session.getRootSubset()));

    // need at least two selected subsets for set operation
    boolean enableSetOps = (Iterables.size(selectedSubsets) > 1);

    makeUnion.setEnabled(enableSetOps);
    makeIntersection.setEnabled(enableSetOps);
    makeDifference.setEnabled(enableSetOps);
}