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:dagger2.internal.codegen.InjectConstructorValidator.java

@Override
public ValidationReport<ExecutableElement> validate(ExecutableElement constructorElement) {
    ValidationReport.Builder<ExecutableElement> builder = ValidationReport.Builder.about(constructorElement);
    if (constructorElement.getModifiers().contains(PRIVATE)) {
        builder.addItem(INJECT_ON_PRIVATE_CONSTRUCTOR, constructorElement);
    }//from ww w. ja  v a2s .c o  m

    for (AnnotationMirror qualifier : getQualifiers(constructorElement)) {
        builder.addItem(QUALIFIER_ON_INJECT_CONSTRUCTOR, constructorElement, qualifier);
    }

    for (VariableElement parameter : constructorElement.getParameters()) {
        ImmutableSet<? extends AnnotationMirror> qualifiers = getQualifiers(parameter);
        if (qualifiers.size() > 1) {
            for (AnnotationMirror qualifier : qualifiers) {
                builder.addItem(MULTIPLE_QUALIFIERS, constructorElement, qualifier);
            }
        }
    }

    TypeElement enclosingElement = MoreElements.asType(constructorElement.getEnclosingElement());
    Set<Modifier> typeModifiers = enclosingElement.getModifiers();

    if (typeModifiers.contains(PRIVATE)) {
        builder.addItem(INJECT_INTO_PRIVATE_CLASS, constructorElement);
    }

    if (typeModifiers.contains(ABSTRACT)) {
        builder.addItem(INJECT_CONSTRUCTOR_ON_ABSTRACT_CLASS, constructorElement);
    }

    if (enclosingElement.getNestingKind().isNested() && !typeModifiers.contains(STATIC)) {
        builder.addItem(INJECT_CONSTRUCTOR_ON_INNER_CLASS, constructorElement);
    }

    // This is computationally expensive, but probably preferable to a giant index
    FluentIterable<ExecutableElement> injectConstructors = FluentIterable
            .from(ElementFilter.constructorsIn(enclosingElement.getEnclosedElements()))
            .filter(new Predicate<ExecutableElement>() {
                @Override
                public boolean apply(ExecutableElement input) {
                    return isAnnotationPresent(input, Inject.class);
                }
            });

    if (injectConstructors.size() > 1) {
        builder.addItem(MULTIPLE_INJECT_CONSTRUCTORS, constructorElement);
    }

    ImmutableSet<? extends AnnotationMirror> scopes = getScopes(enclosingElement);
    if (scopes.size() > 1) {
        for (AnnotationMirror scope : scopes) {
            builder.addItem(MULTIPLE_SCOPES, enclosingElement, scope);
        }
    }

    return builder.build();
}

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

/**
 * Returns the {@link BindingType} to use for a collection of requests of the same
 * {@link BindingKey}. This allows factories to only take a single argument for multiple requests
 * of the same key./*from w  w  w . j a  v a  2 s  . c o m*/
 */
BindingType getBindingType(Iterable<DependencyRequest> requests) {
    ImmutableSet<BindingType> classes = FluentIterable.from(requests)
            .transform(request -> getBindingType(request.kind())).toSet();
    if (classes.size() == 1) {
        return getOnlyElement(classes);
    } else if (classes.equals(CONTRIBUTION_TYPES)) {
        return PROVISION;
    } else {
        throw new IllegalArgumentException("Bad set of framework classes: " + classes);
    }
}

From source file:edu.mit.streamjit.util.bytecode.Value.java

/**
 * Registers a use of this Value.  Should only be called by Use itself.
 * @param use the use to add//from w  ww  .jav  a  2 s.c o m
 */
void addUse(Use use) {
    //We assert rather than check because this is for internal use only.
    assert use != null;
    //      assert ReflectionUtils.calledDirectlyFrom(Use.class);
    assert use.getOperand() == this : "Adding use of wrong object" + use + ", " + this;
    ImmutableSet<Use> newUses = ImmutableSet.<Use>builder().addAll(uses).add(use).build();
    assert newUses.size() == uses.size() + 1 : "Adding duplicate use: " + use;
    this.uses = newUses;
}

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

@Override
public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException {
    List<String> specifiedValues = ruleContext.attributes().get("allowed_values", STRING_LIST);
    ImmutableSet<String> values = ImmutableSet.copyOf(specifiedValues);
    Predicate<String> isValidValue = Predicates.in(values);
    if (values.size() != specifiedValues.size()) {
        ImmutableMultiset<String> groupedValues = ImmutableMultiset.copyOf(specifiedValues);
        ImmutableList.Builder<String> duplicates = new ImmutableList.Builder<String>();
        for (Multiset.Entry<String> value : groupedValues.entrySet()) {
            if (value.getCount() > 1) {
                duplicates.add(value.getElement());
            }/*from   w  w  w . j  a v a  2 s.  c o m*/
        }
        ruleContext.attributeError("allowed_values", "cannot contain duplicates, but contained multiple of "
                + Printer.repr(duplicates.build(), '\''));
    }

    String defaultValue = ruleContext.attributes().get("default_value", STRING);
    if (!isValidValue.apply(defaultValue)) {
        ruleContext.attributeError("default_value", "must be one of " + Printer.repr(values.asList(), '\'')
                + ", but was " + Printer.repr(defaultValue, '\''));
    }

    if (ruleContext.hasErrors()) {
        // Don't bother validating the value if the flag was already incorrectly specified without
        // looking at the value.
        return null;
    }

    String value = ruleContext.getFragment(ConfigFeatureFlagConfiguration.class)
            .getFeatureFlagValue(ruleContext.getOwner()).or(defaultValue);

    if (!isValidValue.apply(value)) {
        // TODO(mstaib): When configurationError is available, use that instead.
        ruleContext.ruleError("value must be one of " + Printer.repr(values.asList(), '\'') + ", but was "
                + Printer.repr(value, '\''));
        return null;
    }

    ConfigFeatureFlagProvider provider = ConfigFeatureFlagProvider.create(value, isValidValue);

    return new RuleConfiguredTargetBuilder(ruleContext)
            .setFilesToBuild(NestedSetBuilder.<Artifact>emptySet(STABLE_ORDER))
            .addProvider(RunfilesProvider.class, RunfilesProvider.EMPTY)
            .addProvider(ConfigFeatureFlagProvider.class, provider).addNativeDeclaredProvider(provider).build();
}

From source file:com.google.devtools.build.skyframe.CycleDeduper.java

/**
 * Marks a non-empty list representing a cycle of unique values as being seen and returns true
 * iff the cycle hasn't been seen before, accounting for logical equivalence of cycles.
 *
 * For example, the cycle 'a' -> 'b' -> 'c' -> 'a' is represented by the list ['a', 'b', 'c']
 * and is logically equivalent to the cycle represented by the list ['b', 'c', 'a'].
 *//*ww w. j av  a2 s .c o m*/
public boolean seen(ImmutableList<T> cycle) {
    ImmutableSet<T> cycleMembers = ImmutableSet.copyOf(cycle);
    Preconditions.checkState(!cycle.isEmpty());
    Preconditions.checkState(cycle.size() == cycleMembers.size(),
            "cycle doesn't have unique members: " + cycle);

    if (knownCyclesByMembers.containsEntry(cycleMembers, cycle)) {
        return false;
    }

    // Of the C cycles, suppose there are D cycles that have the same members (but are in an
    // incompatible order). This code path takes O(D * L) time. The common case is that D is
    // very small.
    boolean found = false;
    for (ImmutableList<T> candidateCycle : knownCyclesByMembers.get(cycleMembers)) {
        int startPos = candidateCycle.indexOf(cycle.get(0));
        // The use of a multimap keyed by cycle members guarantees that the first element of 'cycle'
        // is present in 'candidateCycle'.
        Preconditions.checkState(startPos >= 0);
        if (equalsWithSingleLoopFrom(cycle, candidateCycle, startPos)) {
            found = true;
            break;
        }
    }
    // We add the cycle even if it's a duplicate so that future exact copies of this can be
    // processed in O(L) time. We are already using O(CL) memory, and this optimization doesn't
    // change that.
    knownCyclesByMembers.put(cycleMembers, cycle);
    return !found;
}

From source file:org.androidtransfuse.analysis.astAnalyzer.ScopeAnalysis.java

@Override
public void analyzeType(InjectionNode injectionNode, ASTType concreteType, AnalysisContext context) {

    if (injectionNode.getASTType().equals(concreteType)) {

        //type is recognized under a given scope
        ASTType scopedType = context.getInjectionNodeBuilders().getScoped(injectionNode.getTypeSignature());
        if (scopedType != null) {
            ScopeAspectFactory scopeAspectFactory = context.getInjectionNodeBuilders()
                    .getScopeAspectFactory(scopedType);
            injectionNode.addAspect(scopeAspectFactory.buildAspect(context));
        } else {/*from w w w.ja v a 2s  . c  om*/
            //annotated type
            ImmutableSet<ASTAnnotation> scopeAnnotations = FluentIterable.from(concreteType.getAnnotations())
                    .filter(scopePredicate).toSet();

            if (scopeAnnotations.size() > 1) {
                validator.error("Only one scoping may be defined").element(concreteType).build();
            }
            for (ASTAnnotation scopeAnnotation : scopeAnnotations) {
                if (context.getInjectionNodeBuilders().containsScope(scopeAnnotation)) {
                    ScopeAspectFactory scopeAspectFactory = context.getInjectionNodeBuilders()
                            .getScopeAspectFactory(scopeAnnotation.getASTType());
                    injectionNode.addAspect(scopeAspectFactory.buildAspect(context));
                }
            }
        }
    }
}

From source file:info.gehrels.voting.singleTransferableVote.STVElectionCalculationStep.java

private CANDIDATE_TYPE chooseOneOutOfManyCandidates(ImmutableSet<CANDIDATE_TYPE> candidates) {
    if (candidates.size() == 1) {
        return candidates.iterator().next();
    }/* w  w  w  .ja v a  2 s . c o  m*/

    CANDIDATE_TYPE chosenCandidate = null;
    if (candidates.size() > 1) {
        electionCalculationListener.delegatingToExternalAmbiguityResolution(candidates);
        AmbiguityResolverResult<CANDIDATE_TYPE> ambiguityResolverResult = ambiguityResolver
                .chooseOneOfMany(candidates);
        electionCalculationListener.externallyResolvedAmbiguity(ambiguityResolverResult);
        chosenCandidate = ambiguityResolverResult.chosenCandidate;
    }

    return chosenCandidate;
}

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

/**
 * Returns a report containing validation errors for a
 * {@link Multibindings @Multibindings}-annotated type.
 *///  w  w w . j  a v a  2  s .  c  om
public ValidationReport<TypeElement> validate(TypeElement multibindingsType) {
    ValidationReport.Builder<TypeElement> validation = ValidationReport.about(multibindingsType);
    if (!multibindingsType.getKind().equals(INTERFACE)) {
        validation.addError(MUST_BE_INTERFACE, multibindingsType);
    }
    if (!multibindingsType.getTypeParameters().isEmpty()) {
        validation.addError(MUST_NOT_HAVE_TYPE_PARAMETERS, multibindingsType);
    }
    Optional<BindingType> bindingType = bindingType(multibindingsType);
    if (!bindingType.isPresent()) {
        validation.addError(MUST_BE_IN_MODULE, multibindingsType);
    }

    ImmutableListMultimap.Builder<Key, ExecutableElement> methodsByKey = ImmutableListMultimap.builder();
    for (ExecutableElement method : getLocalAndInheritedMethods(multibindingsType, elements)) {
        // Skip methods in Object.
        if (method.getEnclosingElement().equals(objectElement)) {
            continue;
        }
        if (!isPlainMap(method.getReturnType()) && !isPlainSet(method.getReturnType())) {
            validation.addError(METHOD_MUST_RETURN_MAP_OR_SET, method);
            continue;
        }
        ImmutableSet<? extends AnnotationMirror> qualifiers = getQualifiers(method);
        if (qualifiers.size() > 1) {
            for (AnnotationMirror qualifier : qualifiers) {
                validation.addError(TOO_MANY_QUALIFIERS, method, qualifier);
            }
            continue;
        }
        if (bindingType.isPresent()) {
            methodsByKey.put(
                    keyFactory.forMultibindingsMethod(bindingType.get(), asExecutable(method.asType()), method),
                    method);
        }
    }
    for (Map.Entry<Key, Collection<ExecutableElement>> entry : methodsByKey.build().asMap().entrySet()) {
        Collection<ExecutableElement> methods = entry.getValue();
        if (methods.size() > 1) {
            Key key = entry.getKey();
            validation.addError(tooManyMultibindingsMethodsForKey(key, methods), multibindingsType);
        }
    }
    return validation.build();
}

From source file:org.apache.aurora.scheduler.http.LeaderRedirect.java

private Optional<ServiceInstance> getLeader() {
    ImmutableSet<ServiceInstance> hostSet = serviceGroupMonitor.get();
    switch (hostSet.size()) {
    case 0:/*from   w ww .  j  a v  a 2 s  .c o m*/
        LOG.warn("No serviceGroupMonitor in host set, will not redirect despite not being leader.");
        return Optional.absent();
    case 1:
        LOG.debug("Found leader scheduler at {}", hostSet);
        return Optional.of(Iterables.getOnlyElement(hostSet));
    default:
        LOG.error("Multiple serviceGroupMonitor detected, will not redirect: {}", hostSet);
        return Optional.absent();
    }
}

From source file:org.waveprotocol.box.server.persistence.migration.DeltaPreparator.java

private void prepareWave(WaveId waveId) throws PersistenceException, IOException {
    ImmutableSet<WaveletId> waveletIds = store.lookup(waveId);
    log(0, "Wave : " + waveId.toString() + " with " + waveletIds.size() + " wavelets");

    int waveletsTotal = waveletIds.size();
    int waveletsCount = 0;

    // Wavelets/*w ww  . j  a v  a  2  s.  c  o m*/
    for (WaveletId waveletId : waveletIds) {
        waveletsCount++;
        log(1, "Wavelet " + waveletsCount + "/" + waveletsTotal + ": " + waveletId.toString());
        prepareWavelet(WaveletName.of(waveId, waveletId));
    }
}