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

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

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:com.facebook.buck.rules.Manifest.java

/**
 * Adds a new output file to the manifest.
 *//*from w  w w.  ja va2s  . c  o  m*/
public void addEntry(FileHashCache fileHashCache, RuleKey key, SourcePathResolver resolver,
        ImmutableSet<SourcePath> universe, ImmutableSet<SourcePath> inputs) throws IOException {
    int index = 0;
    int[] hashIndices = new int[inputs.size()];
    ImmutableListMultimap<String, SourcePath> sortedUniverse = Multimaps.index(universe,
            sourcePathToManifestHeaderFunction(resolver));
    for (SourcePath input : inputs) {
        String relativePath = sourcePathToManifestHeader(input, resolver);
        ImmutableList<SourcePath> paths = sortedUniverse.get(relativePath);
        Preconditions.checkState(!paths.isEmpty());
        hashIndices[index++] = addHash(relativePath, hashSourcePathGroup(fileHashCache, resolver, paths));
    }
    entries.add(new Pair<>(key, hashIndices));
}

From source file:org.sleuthkit.autopsy.timeline.ui.detailview.EventClusterNode.java

@Override
EventNodeBase<?> createChildNode(EventStripe stripe) {
    ImmutableSet<Long> eventIDs = stripe.getEventIDs();
    if (eventIDs.size() == 1) {
        //If the stripe is a single event, make a single event node rather than a stripe node.
        SingleEvent singleEvent = getController().getEventsModel()
                .getEventById(Iterables.getOnlyElement(eventIDs)).withParent(stripe);
        return new SingleEventNode(getChartLane(), singleEvent, this);
    } else {//from   w  w w  .ja  v  a 2  s. co  m
        return new EventStripeNode(getChartLane(), stripe, this);
    }
}

From source file:dagger.internal.codegen.ResolvedBindings.java

/**
 * The binding type for these bindings. If there are {@link #multibindingDeclarations()} or {@link
 * #subcomponentDeclarations()} but no {@link #bindings()}, returns {@link BindingType#PROVISION}.
 *
 * @throws IllegalStateException if {@link #isEmpty()} or the binding types conflict
 *///from   ww  w  .ja v a2 s.c  om
@Override
public BindingType bindingType() {
    checkState(!isEmpty(), "empty bindings for %s", bindingKey());
    if (bindings().isEmpty()
            && (!multibindingDeclarations().isEmpty() || !subcomponentDeclarations().isEmpty())) {
        // Only multibinding declarations, so assume provision.
        return BindingType.PROVISION;
    }
    ImmutableSet<BindingType> bindingTypes = bindingTypes();
    checkState(bindingTypes.size() == 1, "conflicting binding types: %s", bindings());
    return getOnlyElement(bindingTypes);
}

From source file:org.bugkillers.bus.eventbus.SubscriberRegistry_.java

/**
 * Gets an iterator representing an immutable snapshot of all subscribers to the given event at
 * the time this method is called./*from w ww  .j  a  v a  2s  . c  o m*/
 */
Iterator<Subscriber_> getSubscribers(Object event) {
    ImmutableSet<Class<?>> eventTypes = flattenHierarchy(event.getClass());

    List<Iterator<Subscriber_>> subscriberIterators = Lists.newArrayListWithCapacity(eventTypes.size());

    for (Class<?> eventType : eventTypes) {
        CopyOnWriteArraySet<Subscriber_> eventSubscribers = subscribers.get(eventType);
        if (eventSubscribers != null) {
            // eager no-copy snapshot
            subscriberIterators.add(eventSubscribers.iterator());
        }
    }

    return Iterators.concat(subscriberIterators.iterator());
}

From source file:es.upm.dit.xsdinferencer.conversion.converterimpl.automatontoregex.ChareConverter.java

/**
 * Given an equivalence class and an automaton, it creates a factor, which is correctly wrapped depending on the source words info of the given automaton.
 * @param eqClass the equivalence class.
 * @param automaton the automaton./* ww  w.j  a  v  a2s . c  o  m*/
 * @return a wrapped factor.
 */
protected RegularExpression generateWrappedFactorRegularExpression(EquivalenceClass eqClass,
        ExtendedAutomaton automaton) {
    RegularExpression unwrappedFactor;
    if (eqClass.size() == 1) {
        unwrappedFactor = eqClass.iterator().next();
    } else {
        ImmutableSet<SchemaElement> elementsOfFactor = ImmutableSet.copyOf(eqClass);
        unwrappedFactor = new Choice(elementsOfFactor.toArray(new RegularExpression[elementsOfFactor.size()]));
    }
    Map<String, Integer> factorMinMaxOccurrences = automaton.getFactorMinMaxOccurrences(eqClass);
    int max = factorMinMaxOccurrences.get("max");
    int min = factorMinMaxOccurrences.get("min");
    RegularExpression factor = unwrappedFactor;
    if (min == 1 && max == 1) {
        factor = unwrappedFactor;
    } else if (min == 0 && max == 1) {
        factor = new Optional(unwrappedFactor);
    } else if (min == 0 && max > 1) {
        factor = new Repeated(unwrappedFactor);
    } else if (min > 0 && max > 1) {
        factor = new RepeatedAtLeastOnce(unwrappedFactor);
    } else {
        throw new IllegalArgumentException("For the equivalence class: " + eqClass.toString()
                + " getFactorMinMaxOccurrences() method has returned min=" + min + " max=" + max
                + " which does not make sense.\n"
                + "The only way that this may have happened is that an automaton with invalid sources word info had been provided.");
    }
    return factor;
}

From source file:paperparcel.PaperParcelProcessingStep.java

private void printMessages(PaperParcelDescriptor.NonWritableFieldsException e) {
    ImmutableSet<ExecutableElement> validConstructors = e.allNonWritableFieldsMap().keySet();
    ImmutableSet<ExecutableElement> invalidConstructors = e.unassignableConstructorParameterMap().keySet();

    if (validConstructors.size() > 0) {
        // Log errors for each non-writable field in each valid constructor
        for (ExecutableElement validConstructor : validConstructors) {
            ImmutableList<VariableElement> nonWritableFields = e.allNonWritableFieldsMap()
                    .get(validConstructor);
            for (VariableElement nonWritableField : nonWritableFields) {
                String fieldName = nonWritableField.getSimpleName().toString();
                messager.printMessage(Diagnostic.Kind.ERROR,
                        String.format(ErrorMessages.FIELD_NOT_WRITABLE,
                                asType(nonWritableField.getEnclosingElement()).getQualifiedName(), fieldName,
                                validConstructor.toString(), buildExcludeRulesChecklist()),
                        nonWritableField);
            }/* w  w w .  j  av  a2  s.  co  m*/
        }

    } else {
        // Log errors for unassignable parameters in each invalid constructor
        for (ExecutableElement invalidConstructor : invalidConstructors) {
            ImmutableList<VariableElement> unassignableFields = e.unassignableConstructorParameterMap()
                    .get(invalidConstructor);
            for (VariableElement unassignableField : unassignableFields) {
                String fieldName = unassignableField.getSimpleName().toString();
                messager.printMessage(Diagnostic.Kind.ERROR,
                        String.format(ErrorMessages.UNMATCHED_CONSTRUCTOR_PARAMETER, fieldName,
                                asType(invalidConstructor.getEnclosingElement()).getQualifiedName()),
                        invalidConstructor);
            }
        }
    }
}

From source file:com.axmor.eclipse.typescript.core.index.IndexJob.java

@Override
protected IStatus run(IProgressMonitor monitor) {
    if (changedResources.size() == 0) {
        try {/* ww w .ja va  2 s.com*/
            ResourcesPlugin.getWorkspace().getRoot().accept(new IResourceVisitor() {
                @Override
                public boolean visit(IResource resource) throws CoreException {
                    if (resource.getType() == IResource.FILE
                            && TypeScriptResources.isTypeScriptFile(resource.getName())) {
                        String path = resource.getFullPath().toString();
                        if (indexer.checkFile(path, resource.getLocation().toFile().lastModified())) {
                            changedResources.add(path);
                        }
                    }
                    return true;
                }
            });
        } catch (CoreException e) {
            throw Throwables.propagate(e);
        }
    }

    ImmutableSet<String> changed = null;

    synchronized (changedResources) {
        changed = ImmutableSet.copyOf(changedResources);
        changedResources.clear();
    }

    try {
        monitor.beginTask("Indexing TypeScript source files", changed.size());
        for (String path : changed) {
            monitor.worked(1);
            indexer.indexFile(path);
            if (monitor.isCanceled()) {
                indexer.close();
                return Status.CANCEL_STATUS;
            }
        }
        monitor.done();
        return Status.OK_STATUS;
    } finally {
        schedule(WAIT_PERIOD_MS);
    }
}

From source file:dagger.internal.codegen.DuplicateBindingsValidator.java

private String incompatibleBindingsMessage(Key key, ImmutableSet<Binding> duplicateBindings,
        BindingGraph graph) {/* w  w  w .  j  a  va  2 s  .c  o  m*/
    ImmutableSet<dagger.model.Binding> multibindings = duplicateBindings.stream()
            .filter(binding -> binding.kind().isMultibinding()).collect(toImmutableSet());
    verify(multibindings.size() == 1, "expected only one multibinding for %s: %s", key, multibindings);
    StringBuilder message = new StringBuilder();
    java.util.Formatter messageFormatter = new java.util.Formatter(message);
    messageFormatter.format("%s has incompatible bindings or declarations:\n", key);
    message.append(INDENT);
    dagger.model.Binding multibinding = getOnlyElement(multibindings);
    messageFormatter.format("%s bindings and declarations:", multibindingTypeString(multibinding));
    formatDeclarations(message, 2, declarations(graph, multibindings));

    Set<dagger.model.Binding> uniqueBindings = Sets.filter(duplicateBindings,
            binding -> !binding.equals(multibinding));
    message.append('\n').append(INDENT).append("Unique bindings and declarations:");
    formatDeclarations(message, 2, Sets.filter(declarations(graph, uniqueBindings),
            declaration -> !(declaration instanceof MultibindingDeclaration)));
    return message.toString();
}

From source file:org.jclouds.glesys.compute.GleSYSComputeServiceAdapter.java

@Override
public Iterable<Hardware> listHardwareProfiles() {
    Set<? extends Location> locationsSet = locations.get();
    ImmutableSet.Builder<Hardware> hardwareToReturn = ImmutableSet.builder();

    // do this loop after dupes are filtered, else OOM
    Set<OSTemplate> images = listImages();

    for (Entry<String, AllowedArgumentsForCreateServer> platformToArgs : api.getServerApi()
            .getAllowedArgumentsForCreateByPlatform().entrySet())
        for (String datacenter : platformToArgs.getValue().getDataCenters())
            for (int diskSizeGB : platformToArgs.getValue().getDiskSizesInGB().getAllowedUnits())
                for (int cpuCores : platformToArgs.getValue().getCpuCoreOptions().getAllowedUnits())
                    for (int memorySizeMB : platformToArgs.getValue().getMemorySizesInMB().getAllowedUnits()) {
                        ImmutableSet.Builder<String> templatesSupportedBuilder = ImmutableSet.builder();
                        for (OSTemplate template : images) {
                            if (template.getPlatform().equals(platformToArgs.getKey())
                                    && diskSizeGB >= template.getMinDiskSize()
                                    && memorySizeMB >= template.getMinMemSize())
                                templatesSupportedBuilder.add(template.getName());
                        }//ww  w  .j a  v a  2 s  .com
                        ImmutableSet<String> templatesSupported = templatesSupportedBuilder.build();
                        if (templatesSupported.size() > 0)
                            hardwareToReturn.add(new HardwareBuilder().ids(String.format(
                                    "datacenter(%s)platform(%s)cpuCores(%d)memorySizeMB(%d)diskSizeGB(%d)",
                                    datacenter, platformToArgs.getKey(), cpuCores, memorySizeMB, diskSizeGB))
                                    .ram(memorySizeMB)
                                    .processors(ImmutableList.of(new Processor(cpuCores, 1.0)))
                                    .volumes(ImmutableList
                                            .<Volume>of(new VolumeImpl((float) diskSizeGB, true, true)))
                                    .hypervisor(platformToArgs.getKey())
                                    .location(find(locationsSet, LocationPredicates.idEquals(datacenter)))
                                    .supportsImage(ImagePredicates.idIn(templatesSupported)).build());
                    }

    return hardwareToReturn.build();
}

From source file:dagger.internal.codegen.InjectBindingRegistry.java

@CanIgnoreReturnValue
Optional<ProvisionBinding> getOrFindProvisionBinding(Key key) {
    checkNotNull(key);//  w w w. ja va 2  s  . com
    if (!key.isValidImplicitProvisionKey(types)) {
        return Optional.empty();
    }
    ProvisionBinding binding = provisionBindings.getBinding(key);
    if (binding != null) {
        return Optional.of(binding);
    }

    // ok, let's see if we can find an @Inject constructor
    TypeElement element = MoreElements.asType(types.asElement(key.type()));
    ImmutableSet<ExecutableElement> injectConstructors = injectedConstructors(element);
    switch (injectConstructors.size()) {
    case 0:
        // No constructor found.
        return Optional.empty();
    case 1:
        return tryRegisterConstructor(Iterables.getOnlyElement(injectConstructors), Optional.of(key.type()),
                true);
    default:
        throw new IllegalStateException("Found multiple @Inject constructors: " + injectConstructors);
    }
}